Terraform中能否通过嵌套count.index实现多AWS API Gateway域名与多路径映射的关联配置?
Absolutely, you can implement this 2D matrix-style mapping where each API Gateway domain name gets paired with all 4 of your API/stage combinations in Terraform. While you can't directly use nested count.index values, we can use Terraform's setproduct function to generate all required domain-API pairs, then create resources based on that list.
Step 1: Generate Domain-API Pairings
First, create a local value that combines the indices of your domain names and your API/stage resources into a list of pairs. This gives us every possible combination (the Cartesian product) of domains and APIs:
locals { # Get indices for all created domain names (0 to count-1) domain_indices = range(length(aws_api_gateway_domain_name.apigw_domain_name)) # Indices for your 4 API/stage resources (0,1,2,3) api_indices = range(4) # Generate all domain-api index pairs (e.g., [0,0], [0,1], ..., [n-1,3]) domain_api_pairs = setproduct(local.domain_indices, local.api_indices) }
Step 2: Create Base Path Mappings for Each Pair
Now, use the domain_api_pairs list to create your aws_api_gateway_base_path_mapping resources. Each entry in the list corresponds to one domain-api pairing:
resource "aws_api_gateway_base_path_mapping" "api_gateway_base_path_mapping" { # One resource per domain-api pair count = length(local.domain_api_pairs) # Extract the domain index from the current pair domain_name = aws_api_gateway_domain_name.apigw_domain_name[local.domain_api_pairs[count.index][0]].domain_name # Extract the API index from the current pair api_id = aws_api_gateway_rest_api.apigw[local.domain_api_pairs[count.index][1]].id stage_name = aws_api_gateway_stage.stage[local.domain_api_pairs[count.index][1]].stage_name }
How This Works
- When
var.api_server_custom_domain_nameis non-empty (soaws_api_gateway_domain_name.apigw_domain_namehas count=1 or more),local.domain_indiceswill include all indices for those domains. setproductcombines each domain index with each API index, creating a list where every domain is paired with every one of your 4 APIs.- The
counton the base path mapping resource will automatically match the total number of pairs, ensuring each domain gets all 4 mappings. - If no domains are created (count=0),
local.domain_indiceswill be empty, solocal.domain_api_pairswill also be empty, and no base path mappings will be created—perfect for conditional behavior.
Can You Use Nested count.index?
No, Terraform doesn't support directly nesting count.index values within the same resource block. You can't reference count.index for one resource while also using another count.index for a different list in the same argument. However, the setproduct approach achieves the same goal by precomputing all required pairs, letting you access both indices via the pre-generated list entries.
内容的提问来源于stack exchange,提问作者pankaj_m05

