当前,我正在使用terraform工作区将相同的代码部署到多个环境中。但是现在,我只能在特定工作区中引用资源。
代码示例
resource "aws_security_group" "testing-ec2" {
name = "${local.env}-testing-ec2"
vpc_id = "${aws_vpc.vpc.id}"
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
security_groups = ["${local.security-groups}"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["${local.bastion_ip}"]
}
egress {
from_port = 0
to_port = 0
protocol = -1
cidr_blocks = ["0.0.0.0/0"]
}
}
工作区安全组
local {
tf_security-groups = {
dev = ""
stg = "${aws_security_group.test-private-alb.id}"
qa = "${aws_security_group.test1-private-alb.id}"
prod = "${aws_security_group.test2-private-alb.id}"
}
security-groups = "${lookup(local.tf_security-groups,local.env)}"
}
当我尝试应用到stg工作区时,出现此错误
* local.tf_security-groups: local.tf_security-groups: Resource 'aws_security_group.test1-private-alb' not found for variable 'aws_security_group.test1-private-alb.id'
答案 0 :(得分:0)
您可以使用数据源terraform_remote_state
来筛选状态,但还必须将每个安全组id
转换为输出。
data "terraform_remote_state" "this" {
backend = "s3"
workspace = "stg"
config {
bucket = ""
key = ""
region = ""
}
}
使用aws_security_group
数据源会更清洁。
locals {
env = "qa"
security_group_map = {
stg = data.aws_security_group.test_private_alb.id
qa = data.aws_security_group.test1_private_alb.id
prod = data.aws_security_group.test2_private_alb.id
}
security_groups = lookup(local.security_group_map, local.env, "")
}
data "aws_security_group" "test_private_alb" {
name = "test_private_alb"
}
data "aws_security_group" "test1_private_alb" {
name = "test1_private_alb"
}
data "aws_security_group" "test2_private_alb" {
name = "test2_private_alb"
}