我正在使用 Terraform 开发要在 AWS 中使用的基础架构(IaC)。为了测试,我使用的是EC2实例。
此代码必须能够跨多个帐户进行部署,并且**每个开发人员应具有多个区域(环境)**。这是一个示例:
帐户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.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
帐户的值。我该如何解决?
另一方面,采用这种结构,是否有可能实现模块?
答案 0 :(得分:0)
您可以使用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}"
}
您甚至可以结合使用这两种方法!