问题描述
我有以下情况,我想知道我做错了什么,因为我确信我不应该仅仅因为一个条件而将我的代码加倍.
I have the following and I want to know what I am doing wrong, as I am sure I shouldn't have to double my code just because of a condition.
所以我想做:
variable "https" { value = true }
resource "aws_security_group" "http_instance_sg" {
count = "${var.https ? 0 : 1}"
......
}
resource "aws_security_group" "https_instance_sg" {
count = "${var.https ? 1 : 0}"
......
}
resource "aws_elb" "fe_elb" {
security_groups = ["${var.https ? aws_aws_security_group.https_instance_sg.id : aws_aws_security_group.http_instance_sg.id}"]
.....
}
但是当我这样做时,terraform 抱怨找不到 http_instance_sg
,我知道它还没有构建,但我肯定不必加倍所有代码并且拥有:
But when I do this terraform complains that http_instance_sg
cant be found, which I get it hasn't be built, but surely I dont have to double up on all the code and have:
resource "aws_elb" "http_fe_elb" {
count = "${var.https ? 0 : 1}"
security_groups = ["${aws_aws_security_group.http_instance_sg.id}"]
.....
}
resource "aws_elb" "https_fe_elb" {
count = "${var.https ? 1 : 0}"
security_groups = ["${aws_aws_security_group.https_instance_sg.id}"]
.....
}
推荐答案
您当前使用计数定义代码的方式意味着资源的响应是一个列表.这意味着您将需要以不同的方式访问这些值
The way you are currently defining the code with a count means that the response of the resource is a list. This means you will need to access the values differently
resource "aws_elb" "fe_elb" {
security_groups = ["${var.https ? element(aws_security_group.https_instance_sg.*.id,0) : element(aws_security_group.http_instance_sg.*.id,0)}"]
.....
}
值得注意的是,如果您尝试使用此方法访问一个为空的列表,则会出现错误.
It's worth noting that you will get an error if you try to access a list that is empty using this method.
这意味着您需要为每个值连接一个空值以确保响应of element 不抛出.
This means you will need to concat an empty value to each to ensure the response of element doesn't throw.
使用 concat 的示例
"${var.https ? element(concat(aws_security_group.https_instance_sg.*.id, list("")), 0) : element(concat(aws_security_group.http_instance_sg.*.id, list("")), 0)
不同的方法
如果没有看到代码,我可能会在这里问是否有更简单的方法可以使用 security_group_rule
Without seeing the code I might ask here if there is an easier way to achieve what you are trying to do using a security_group_rule
variable "https" { value = true }
resource "aws_security_group" "instance_sg" {
# notice we no longer have a count here
}
resource "aws_elb" "fe_elb" {
security_groups = ["${aws_security_group.instance_sg.id}"]
.....
}
resource "aws_security_group_rule" "http" {
count = "${var.https ? 0 : 1}"
.... http definitions
security_group_id = "${aws_security_group.instance_sg.id}"
}
resource "aws_security_group_rule" "https" {
count = "${var.https ? 0 : 1}"
.... https definitions
security_group_id = "${aws_security_group.instance_sg.id}"
}
这篇关于terraform 条件资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!