Terraform - 如何在条件运算符中使用有条件创建的资源输出? [英] Terraform - How to use conditionally created resource's output in conditional operator?
问题描述
如果用户不提供 vpc id,我必须创建 aws_vpc 资源.之后,我应该使用该 VPC 创建资源.
I have a case where I have to create an aws_vpc resource if the user does not provide vpc id. After that I am supposed to create resources with that VPC.
现在,我在创建 aws_vpc
资源时应用条件.例如,仅当 existing_vpc
为 false 时才创建 VPC:
Now, I am applying conditionals while creating an aws_vpc
resource. For example, only create VPC if existing_vpc
is false:
count = "${var.existing_vpc ? 0 : 1}"
接下来,例如,我必须在 VPC 中创建节点.如果 existing_vpc
为真,则使用 var.vpc_id
,否则使用从 aws_vpc
资源计算的 VPC ID.
Next, for example, I have to create nodes in the VPC. If the existing_vpc
is true, use the var.vpc_id
, else use the computed VPC ID from aws_vpc
resource.
但是,问题是,如果 existing_vpc
为真,aws_vpc
将不会创建新资源,并且三元条件无论如何都会尝试检查 aws_vpc
资源是否正在创建.如果它没有被创建,则 terraform 错误.
But, the issue is, if existing_vpc
is true, aws_vpc
will not create a new resource and the ternary condition is anyways trying to check if the aws_vpc
resource is being created or not. If it doesn't get created, terraform errors out.
在 aws_subnet
上使用条件运算符时的错误示例:
An example of the error when using conditional operator on aws_subnet
:
Resource 'aws_subnet.xyz-subnet' not found for variable 'aws_subnet.xyz-subnet.id'
导致错误的代码是:
subnet_id = "${var.existing_vpc ? var.subnet_id : aws_subnet.xyz-subnet.id}"
如果两者相互依赖,我们如何创建条件资源并基于它们为其他配置赋值?
If both things are dependent on each other, how can we create conditional resources and assign values to other configuration based on them?
推荐答案
您可以访问动态创建的模块和资源,如下所示
You can access dynamically created modules and resources as follows
output "vpc_id" {
value = length(module.vpc) > 0 ? module.vpc[*].id : null
}
- 如果 count = 0,则输出为空
- 如果计数 >0,输出是 vpc id 列表
如果 count = 1 并且您希望接收单个 vpc id,您可以指定:
If count = 1 and you want to receive a single vpc id you can specify:
output "vpc_id" {
value = length(module.vpc) > 0 ? one(module.vpc).id : null
}
这篇关于Terraform - 如何在条件运算符中使用有条件创建的资源输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!