使用Terraform管理多个AWS区域

sko*_*hrs 6 amazon-web-services terraform

有人可以给我一个示例,说明如何基于变量映射以编程方式创建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"
}
Run Code Online (Sandbox Code Playgroud)

错误:

$ terraform plan
* provider.aws.${lookup(var.aws_regions[count.index], "alias")}: count.index: count.index is only valid within resources
Run Code Online (Sandbox Code Playgroud)

sko*_*hrs 6

事实证明,Terraform 提供程序处理发生的很早,当前版本 (v.0.11.3) 目前不支持提供程序的变量插值。我确实发现了一个不太糟糕的解决方法,但它需要大量的代码重复。

主文件

# 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"
  }
}
Run Code Online (Sandbox Code Playgroud)

云表/main.tf

provider "aws" {
  alias = "region"
}

# CloudWatch Log Groups
resource "aws_cloudwatch_log_group" "linux" {
  name     = "Linux"
  provider = "aws.region"

  tags {
    OS = "Linux"
  }
}
Run Code Online (Sandbox Code Playgroud)