Is there a way AND/OR conditional operator in terraform?

后端 未结 4 1884
离开以前
离开以前 2020-12-29 07:27

Is there a way to use something like this in Terraform?

count = \"${var.I_am_true}\"&&\"${var.I_am_false}\"

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 08:27

    Terraform 0.8 added first class support for conditional logic rather than the previous hacky workarounds.

    This uses the classic ternary syntax so now you can do something like this:

    variable "env" { default = "development" }
    
    resource "aws_instance" "production_server" {
      count = "${var.env == "production" ? 1 : 0}"
      ...
    }
    

    Now this will only create the production_server EC2 instance when env is set to "production".

    You can also use it in other places too such as setting a variable/parameter like this:

    variable "env" { default = "development" }
    variable "production_variable" { default = "foo" }
    variable "development_variable" { default = "bar" }
    
    output "example" {
      value = "${var.env == "production" ? var.production_variable : var.development_variable}"
    }
    

    One thing to be aware of is that Terraform actually evaluates both sides before then choosing the value used in the ternary statement rather than lazily evaluating just the side of the ternary that the logic will trigger.

    This means you can't do something like this recent example of me trying to hack around an issue with the aws_route53_zone data source:

    variable "vpc"    {}
    variable "domain" {}
    
    variable "private_zone"  { default = "true" }
    
    data "aws_vpc" "vpc" {
      filter {
        name   =   "tag-key"
        values = [ "Name" ]
      }
      filter {
        name   =   "tag-value"
        values = [ "${var.vpc}" ]
      }
    }
    
    data "aws_route53_zone" "private_zone" {
      count        = "${var.private_zone == "true" ? 1 : 0}"
      name         = "${var.domain}"
      vpc_id       = "${data.aws_vpc.vpc.id}"
      private_zone = "true"
    }
    
    data "aws_route53_zone" "public_zone" {
      count        = "${var.private_zone == "true" ? 0 : 1}"
      name         = "${var.domain}"
      private_zone = "false"
    }
    
    output "zone_id" {
      value = "${var.private_zone == "true" ? data.aws_route53_zone.private_zone.zone_id : data.aws_route53_zone.public_zone.zone_id}"
    }
    

    In the above example this will fail on the plan because either data.aws_route53_zone.private_zone.zone_id or data.aws_route53_zone.public_zone.zone_id is not defined depending on whether public_zone is set to true or false.

提交回复
热议问题