我试图通过将2个ec2实例定义为count来创建2个ec2实例,其中一个实例充当主节点,另一个实例充当工作节点。我想为每个添加两个不同的安全组。如何使用参数“ vpc_security_group_ids”将主安全组附加到一个实例,将工作人员安全组附加到另一个。 我不确定在这种情况下如何应用插值?有任何建议!
Ec2实例:
resource "aws_instance" "tableau_server" {
count = 2
availability_zone = "${lookup(var.availability_zones, count.index)}"
ami = "${var.ami_id}"
instance_type = "${var.instance_type}"
key_name = "${var.key_name}"
subnet_id = "${var.subnet_id}"
associate_public_ip_address = true
vpc_security_group_ids = [
"${aws_security_group.tableau_server_sg_master.id}",
"${aws_security_group.tableau_server_sg_worker.id}",
]
root_block_device {
volume_type = "gp2"
volume_size = "${var.volume_size}"
delete_on_termination = true
}
tags {
Name = "tableau-server_${count.index}_${var.env}"
Terraform = "true"
Environment = "${var.env}"
}
}
答案 0 :(得分:1)
作为快速解决方案,您可以尝试这样做:
resource "aws_instance" "tableau_server" {
[...]
vpc_security_group_ids = ["${count.index < 1 ?
aws_security_group.tableau_server_sg_master.id :
aws_security_group.tableau_server_sg_worker.id}"]
[...]
tags {
Name = "tableau-server_${count.index < 1 ? "master" : format("_worker_%d_", count.index)}_${var.env}"
[...]
}
}
如果您只有一个主管和多个工作人员,则此方法有效。对于不止一个工人,您需要更改条件并使其更具动态性(例如,使用变量作为主工人和工人的数量)
如果您想进一步了解“条件”(terraform的if / else ^^),请执行以下操作: https://www.terraform.io/docs/configuration/interpolation.html#conditionals