请问有谁可以举例说明如何基于变量映射以编程方式创建Terraform提供程序别名?这是我尝试过的,但我收到了以下错误:
variable "aws_regions" {
default = [
{
region = "us-east-1"
alias = "default"
},
{
region = "us-east-2"
alias = "useast2"
},
{
region = "us-west-1"
alias = "uswest1"
},
{
region = "us-west-2"
alias = "uswest2"
},
{
region = "eu-central-1"
alias = "eucent1"
}
]
}
provider "aws" {
count = "${length(var.aws_regions)}"
region = "${lookup(var.aws_regions[count.index], "region")}"
alias = "${lookup(var.aws_regions[count.index], "alias")}"
}
# CloudWatch Log Groups
resource "aws_cloudwatch_log_group" "linux" {
count = "${length(var.aws_regions)}"
provider = "aws.${lookup(var.aws_regions[count.index], "alias")}"
name = "Linux"
}
错误:
$ terraform plan
* provider.aws.${lookup(var.aws_regions[count.index], "alias")}: count.index: count.index is only valid within resources
答案 0 :(得分:2)
事实证明,Terraform提供程序处理很早就发生了,当前版本(v.0.11.3)目前不支持提供程序的变量插值。我确实发现了一个并不太可怕的解决方法,但它需要大量的代码重复。
<强> main.tf 强>
# Default Region
provider "aws" {
region = "us-east-1"
version = "~> 1.8"
}
provider "aws" {
alias = "us-east-1"
region = "us-east-1"
}
provider "aws" {
alias = "us-east-2"
region = "us-east-2"
}
provider "aws" {
alias = "us-west-1"
region = "us-west-1"
}
provider "aws" {
alias = "us-west-2"
region = "us-west-2"
}
provider "aws" {
alias = "eu-central-1"
region = "eu-central-1"
}
# CloudTrail Setup in Default Region
module "cloudtrail" {
source = "./cloudtrail"
}
# CloudWatch Setup per Region
module "us-east-1_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-east-1"
}
}
module "us-east-2_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-east-2"
}
}
module "us-west-1_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-west-1"
}
}
module "us-west-2_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-west-2"
}
}
module "eu-central-1_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.eu-central-1"
}
}
<强>的CloudWatch / main.tf 强>
provider "aws" {
alias = "region"
}
# CloudWatch Log Groups
resource "aws_cloudwatch_log_group" "linux" {
name = "Linux"
provider = "aws.region"
tags {
OS = "Linux"
}
}
答案 1 :(得分:0)
使用工作空间-可用于可复制的用例,例如开发环境和多区域。 https://www.terraform.io/docs/state/workspaces.html