【问题标题】:Terraform - Multiple accounts with multiple environments (regions)Terraform - 具有多个环境(区域)的多个帐户
【发布时间】:2021-01-15 21:59:26
【问题描述】:

我正在使用 Terraform 开发我希望在 AWS 中拥有的基础架构 (IaC)。为了测试,我使用的是 EC2 实例。

此代码必须能够部署跨多个帐户和**每个开发者的多个区域(环境)**。这是一个例子:

account-999

developer1: us-east-2
developer2: us-west-1
developerN: us-east-1

account-666

Staging: us-east-1
Production: eu-west-2

我创建了两个 .tfvars 变量,account-999.env.tfvarsaccount-666.env.tfvars,内容如下:

  • profile="account-999"profile="account-666" 分别

这是我的 main.tf,其中包含带有 EC2 实例的 aws 提供程序:

provider "aws" {
  version = "~> 2.0"
  region  = "us-east-1"
  profile = var.profile
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "HelloWorld"
  }
}

还有variable.tf 文件:

variable "profile" {
  type=string
}

variable "region" {
  description = "Region by developer"
  type = map
  default = {
    developer1 = "us-west-2"
    developer2 = "us-east-2"
    developerN = "ap-southeast-1"
  }
}

但我不确定我是否管理得很好。例如,region 变量仅包含 account-999 帐户的值。我该如何解决? 另一方面,有了这种结构,是否可以实现模块?

【问题讨论】:

  • 使用模块和提供者别名可以最好地解决区域问题,特别是如果您使用 0.13 和新的模块元参数功能。

标签: amazon-web-services terraform environment terraform-provider-aws infrastructure-as-code


【解决方案1】:

您可以使用provider alias 来完成此操作。更多关于提供者别名的信息可以在here找到。

provider "aws" {
  region = "us-east-1"
}

provider "aws" {
  alias  = "west"
  region = "us-west-2"
}

resource "aws_instance" "foo" {
  provider = aws.west
  # ...
}

另一种查看方式是使用terraform workspaces。这是一个例子:

terraform workspace new account-999
terraform workspace new account-666

那么这是您的 aws 凭证文件的示例:

[account-999]
aws_access_key_id=xxx
aws_secret_access_key=xxx

[account-666]
aws_access_key_id=xxx
aws_secret_access_key=xxx

可以在提供程序块中使用对该帐户的引用:

provider "aws" {
    region  = "us-east-1"
    profile = "${terraform.workspace}"
}

你甚至可以结合这两种方法!

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 2020-03-11
    • 2019-04-28
    • 2022-01-02
    • 2019-04-05
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多