Terraform ec2 实例类型有条件吗?

lef*_*nut 0 amazon-ec2 amazon-web-services terraform terraform-provider-aws

我想根据 .tfvars 文件的条件创建 Spot 实例。否则我想要一个常规的 ec2 实例。我知道有一个三元条件,但不确定如何正确使用它。

spot = var.spot_instance ? instance_market_options {
    market_type = "spot"
  } : 
Run Code Online (Sandbox Code Playgroud)
resource "aws_launch_template" "foo" {
  name = "foo"
  iam_instance_profile {
    name = "test"
  }
  image_id = "ami-test"
  instance_market_options {
    market_type = "spot"
  }
  instance_type = "t2.micro"
}
Run Code Online (Sandbox Code Playgroud)

或者可能是这个?

instance_market_options = var.spot_instance ? {
    market_type = "spot" 
  } : 
Run Code Online (Sandbox Code Playgroud)

Mar*_*o E 5

由于代码片段看起来并不完整,因此应该如下所示:

resource "aws_launch_template" "foo" {
  name = "foo"
  iam_instance_profile {
    name = "test"
  }
  image_id = "ami-test"

  dynamic "instance_market_options" {
    for_each = var.spot_instance ? [1] : []
    content {
      market_type = "spot"
    }
  }
  instance_type = "t2.micro"
}
Run Code Online (Sandbox Code Playgroud)

for_each这是使用元参数和块的组合dynamic。此外,您不能使用*.tfvars文件中的任何条件。