百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

terraform-provider-azurecaf

> 编程语言
开源

Terraform 提供程序,用于 Azure 的 Terraform 平台工程

186 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

Terraform 提供程序,用于 Azure 的 Terraform 平台工程

Azurecaf Terraform Provider

The azurecaf provider implements a set of methodologies for naming convention implementation, including the default Microsoft Cloud Adoption Framework for Azure recommendations as per the Azure naming and tagging best practices. Please note this project is not part of Azure Cloud Adoption Framework and is supported by the community, not by Microsoft Support.

Key Features

The Azure CAF provider allows you to:

  • ️ Generate compliant Azure resource names following CAF guidelines and Azure naming restrictions
  • ** Clean and sanitize inputs** to ensure compliance with allowed patterns for each Azure resource
  • ** Add random characters** to resource names for uniqueness
  • ️ Handle prefixes and suffixes (either manual or as per Azure CAF resource conventions)
  • ✅ Validate existing names using passthrough mode
  • ** Support multiple naming conventions** (CAF classic, CAF random, passthrough, etc.)
  • ** Generate names for 405 Azure resource types** with accurate validation rules

Quick Start

Installation

Add the provider to your Terraform configuration:

hcl
terraform {
  required_providers {
    azurecaf = {
      source  = "aztfmod/azurecaf"
      version = "~> 1.2.32"  # Use the latest version
    }
  }
}

Basic Usage

Generate an Azure-compliant resource group name:

hcl
# Using data source (recommended - evaluated at plan time)
data "azurecaf_name" "rg_example" {
  name          = "myproject"
  resource_type = "azurerm_resource_group"
  prefixes      = ["demo"]
  suffixes      = ["001"]
  random_length = 5
  clean_input   = true
}

resource "azurerm_resource_group" "example" {
  name     = data.azurecaf_name.rg_example.result
  location = "East US"
}

output "resource_group_name" {
  value = data.azurecaf_name.rg_example.result
  # Output: rg-demo-myproject-001-a1b2c
}

Comprehensive Examples

Example 1: Simple Resource Naming

Generate names with automatic resource type prefixes:

hcl
data "azurecaf_name" "storage_account" {
  name          = "mydata"
  resource_type = "azurerm_storage_account"
  random_length = 3
}

resource "azurerm_storage_account" "example" {
  name                     = data.azurecaf_name.storage_account.result
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}
# Result: "stmydata123" (st = storage account slug, mydata = name, 123 = random)

Example 2: Multiple Resources with Consistent Naming

Generate names for multiple related resources:

…

Example 3: Using Resource (vs Data Source)

For cases where you need to generate multiple resource names:

hcl
resource "azurecaf_name" "multiple_resources" {
  name           = "myapp"
  resource_type  = "azurerm_app_service"
  resource_types = [
    "azurerm_app_service_plan",
    "azurerm_application_insights"
  ]
  prefixes       = ["prod"]
  suffixes       = ["web"]
  random_length  = 3
  clean_input    = true
}

# Access individual names:
# Primary: azurecaf_name.multiple_resources.result
# All: azurecaf_name.multiple_resources.results

Example 4: Passthrough Mode for Validation

Validate existing resource names without modification:

hcl
data "azurecaf_name" "existing_storage" {
  name          = "mystorageaccount123"
  resource_type = "azurerm_storage_account"
  passthrough   = true
}

# Validates that "mystorageaccount123" is compliant with storage account naming rules

Example 5: Advanced Configuration

Complex naming with custom separators and no resource slugs:

hcl
data "azurecaf_name" "custom_vm" {
  name          = "database-server"
  resource_type = "azurerm_linux_virtual_machine"
  prefixes      = ["corp", "prod"]
  suffixes      = ["db", "001"]
  separator     = "_"
  use_slug      = false
  random_length = 4
  clean_input   = true
}

# Result: "corp_prod_database_server_db_001_a1b2"

️ Configuration Reference

Supported Parameters

Parameter Type Description Default
name string Base name for the resource ""
resource_type string Azure resource type (e.g., azurerm_storage_account) Required
resource_types list(string) Additional resource types for multi-resource naming []
prefixes list(string) List of prefixes to prepend []
suffixes list(string) List of suffixes to append []
random_length number Number of random characters to add 0
random_seed number Seed for random generation (0 = time-based) 0
separator string Character to separate name components "-"
clean_input bool Remove non-compliant characters from inputs true
passthrough bool Validate without modification false
use_slug bool Include resource type abbreviation true
error_when_exceeding_max_length bool Fail when generated name exceeds the resource's max length false

Output Attributes

Attribute Description
id Unique identifier for the naming configuration
result Generated name for the primary resource type
results Map of all generated names (when using resource_types)

Supported Azure Resources

This provider supports 405 Azure resource types with accurate naming validation rules. Each resource type has specific constraints for:

  • Minimum and maximum length
  • Allowed characters and patterns
  • Case sensitivity requirements
  • Uniqueness scope (global, resource group, or parent resource)

Popular Resource Types

Resource Type Slug Min Length Max Length Example Generated Name
azurerm_resource_group rg 1 90 rg-prod-myapp-001
azurerm_storage_account st 3 24 stprodmyapp001
azurerm_key_vault kv 3 24 kv-prod-myapp-001
azurerm_app_service app 2 60 app-prod-myapp-001
azurerm_kubernetes_cluster aks 1 63 aks-prod-myapp-001
azurerm_virtual_machine vm 1 15 vm-prod-001
azurerm_sql_server sql 1 63 sql-prod-myapp-001

View Full Resource Type List

For the complete list of 405 supported resource types, see the Resource Types Documentation.

Advanced Usage

Environment-Based Naming

hcl
locals {
  environment_config = {
    dev = {
      prefix = "dev"
      random_length = 3
    }
    prod = {
      prefix = "prod" 
      random_length = 5
    }
  }
  
  current_env = local.environment_config[var.environment]
}

data "azurecaf_name" "app_service" {
  name          = var.application_name
  resource_type = "azurerm_app_service"
  prefixes      = [local.current_env.prefix]
  random_length = local.current_env.random_length
}

Integration with Terraform Modules

hcl
# In your module
variable "project_name" {
  description = "Name of the project"
  type        = string
}

variable "environment" {
  description = "Environment (dev, test, prod)"
  type        = string
}

data "azurecaf_name" "resources" {
  for_each = toset([
    "azurerm_resource_group",
    "azurerm_storage_account", 
    "azurerm_key_vault"
  ])
  
  name          = var.project_name
  resource_type = each.key
  prefixes      = [var.environment]
  random_length = 3
}

output "resource_names" {
  value = { for k, v in data.azurecaf_name.resources : k => v.result }
}

Troubleshooting

Common Issues

Issue: Names too long for resource type

hcl
# Problem: Generated name exceeds Azure limits
data "azurecaf_name" "long_name" {
  name          = "very-long-application-name-that-exceeds-limits"
  resource_type = "azurerm_storage_account"  # max 24 chars
}

# Solution: Use shorter base name or disable slug
data "azurecaf_name" "fixed_name" {
  name          = "shortname"
  resource_type = "azurerm_storage_account"
  use_slug      = false  # Removes 'st' prefix
}

Issue: Invalid characters in resource names

hcl
# Problem: Special characters not allowed
data "azurecaf_name" "invalid_chars" {
  name          = "[email protected]"
  resource_type = "azurerm_app_service"
  clean_input   = false  # Keeps invalid chars
}

# Solution: Enable input cleaning (default)
data "azurecaf_name" "clean_name" {
  name          = "[email protected]"
  resource_type = "azurerm_app_service"
  clean_input   = true   # Removes invalid chars
}

Validation Errors

The provider validates names against Azure requirements and will show specific error messages:

Error: Invalid resource name "my--invalid--name"
│ The generated name contains consecutive separators, which is not allowed for azurerm_storage_account

Testing & Development

The Azure CAF terraform provider includes comprehensive testing to ensure reliability and correctness.

Running Unit Tests

To run the standard unit tests:

bash
go test ./azurecaf/...

To run tests with coverage information:

bash
go test -cover ./azurecaf/...

For a detailed coverage report:

bash
go test -coverprofile=coverage.out ./azurecaf/...
go tool cover -html=coverage.out -o coverage.html

Running Integration Tests

Integration tests verify the provider works correctly with Terraform itself. These tests require setting the TF_ACC environment variable:

bash
# Run all integration tests
TF_ACC=1 go test -v ./azurecaf/... -run="TestAcc"

# Run specific integration tests
TF_ACC=1 go test -v ./azurecaf/... -run="TestAccDataSourcesIntegration"
TF_ACC=1 go test -v ./azurecaf/... -run="TestAccErrorHandling"

Note: Integration tests take longer to run than unit tests.

Test Coverage

The project maintains high test coverage (99.0% of statements) to ensure code quality and reliability. Tests are designed to cover:

  • Basic functionality for all resources and data sources
  • Edge cases and error handling
  • Various resource types and naming conventions
  • Different configuration combinations
  • Environment variable interactions
  • Validation and constraints

Test Organization

The test files are organized as follows:

  • Unit Tests: Basic test files like resource_name_test.go
  • Enhanced Tests: More comprehensive tests in files like enhanced_tests_test.go
  • Integration Tests: Tests with the prefix TestAcc that interact with Terraform directly
  • Error Handling Tests: Tests that verify proper error reporting in edge cases
  • Complete Coverage Tests: Tests designed specifically to achieve maximum code coverage
  • Resource Matrix Tests: Comprehensive validation of all 405 resource types
  • Constraint Tests: Validation of resource naming constraints and limitations

Comprehensive Testing Framework

The provider includes a comprehensive testing framework that validates all 405 Azure resource types:

bash
# Run comprehensive tests for all resource types
make test_all_resources

# Run resource matrix validation (category-based testing and constraint validation)
make test_resource_matrix

# Test resource definition completeness
make test_resource_definitions

This framework ensures:

  • 100% Resource Coverage: All 405 resource types are tested
  • Naming Validation: Each resource type's naming constraints are verified
  • Category Organization: Resources are tested by logical categories (Compute, Networking, etc.)
  • Edge Case Testing: Complex naming scenarios and error conditions are validated

Writing New Tests

When writing new tests, consider the following guidelines:

  1. Unit Tests: Test individual functions and components in isolation

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Go

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言