将 var 与条件计数语句一起使用,但似乎在 Terraform 中无法按预期工作

问题描述 投票:0回答:1

基本上的想法是,当 DEPLOY_GREEN

true
时,它将执行 if 条件并正常工作,但当 DEPLOY_GREEN
false
时,会出现问题,它正在执行预期的 else 条件,但它也会执行此
data "aws_ami" "green-capp-operations"
。这是不应该发生的,因为我已经通过了
deploy_strategy=blue
-var
。因此 terraform plan 向我展示了这种错误,

│ Error: Invalid index

│ 

│   on data_ami.tf line 697, in output "green-example":

│  17:   value = data.aws_ami.green-example[0].id

│     ├────────────────

│     │ data.aws_ami.green-example is empty tuple

为什么要为

deploy_strategy=blue
执行条件计数语句?按照逻辑 tt 应该返回
0
。我错过了什么吗?

Terraform 版本:

v1.0.11

为了更好地理解,我分享如下代码,

Jenkins文件:

booleanParam(name: 'DEPLOY_GREEN', defaultValue: false, description: 'Deploy Green Infra?')

if (params.DEPLOY_GREEN) {
                        echo "DEPLOY_GREEN value: ${params.DEPLOY_GREEN}"
                        sh 'terraform plan -var deploy_strategy=green -out=myplan'

                    } else {
                        echo "DEPLOY_GREEN value: ${params.DEPLOY_GREEN}"
                        sh "terraform plan -var deploy_strategy=blue -out=myplan"
                    }

变量.tf:

variable "deploy_strategy" {
  type = string
}

ami.tf:

data "aws_ami" "green-example" {
  count = var.deploy_strategy == "green" ? 1 : 0
  filter {
    name   = "state"
    values = ["available"]
  }
  filter {
    name   = "tag:Name"
    values = ["${local.env}-${var.deploy_strategy}-example-*"]
    //    name = "name"
    //    values = ["amzn2-ami-hvm*"]
  }
  owners      = ["self"]
  most_recent = true
}

output "green-example" {
  value = data.aws_ami.green-example[0].id
}
count terraform terraform-provider-aws
1个回答
0
投票

你的

green-example
输出是无条件的。因此,当部署策略不是绿色时,您必须选择合适的值。

output "green-example" {
  value = data.aws_ami.green-example[0].id
}

在这种情况下,您可能需要 one 函数,或者

  • 返回 1 长度列表的第一个元素
  • 对于 0 长度的列表返回 null
  • 否则会引发错误

使用示例:

output "green-example" {
  value = one(data.aws_ami.green-example[*].id)
}

*
是一种列表理解,可扩展为
green-example
中所有 id 的列表。因此,在本例中要么是 1 长度的列表,要么是 0 长度的列表。这使得它非常适合与
one()
功能一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.