我正在用Terraform开发我想在AWS中拥有的基础设施(IaC(。为了进行测试,我使用了一个EC2实例。
此代码必须能够部署到多个帐户和**每个开发人员**多个区域(环境(。这是一个例子:
账户-999
developer1: us-east-2
developer2: us-west-1
developerN: us-east-1
帐号-666:
Staging: us-east-1
Production: eu-west-2
我创建了两个.tfvars
变量,account-999.env.tfvars
和account-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
帐户的值。我该如何解决?另一方面,有了这种结构,是否有可能实现模块?
您可以使用provider alias
来实现这一点。有关提供程序别名的更多信息,请访问此处。
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}"
}
你甚至可以将这两种方法结合起来!