Terraform-在变量默认情况下使用数据源输出

时间:2018-08-22 12:51:04

标签: terraform

我正在创建一个模块来启动基本的Web服务器。

我正在尝试获取它,以便如果用户未指定AMI,则使用该区域的ubuntu映像。

我有一个data块来获取该区域的ubuntu 16.04图像的AMI ID,但是由于插值不起作用,我无法将其设置为变量的默认值。

我的模块如下:-

main.tf

resource "aws_instance" "web" {
  ami = "${var.aws_ami}"
  instance_type = "${var.instance_type}"
  security_groups = ["${aws_security_groups.web.id}"]

  tags {
      Name = "WEB_SERVER"
  }
}

resource "aws_security_groups" "web" {
  name = "WEB_SERVER-HTTP-HTTPS-SG"

  ingress {
      from_port = "${var.http_port}"
      to_port = "${var.http_port}"
      protocol = "tcp"
      cidr_blocks = ["0.0.0.0/0"] 
  }

  ingress {
      from_port = "${var.https_port}"
      to_port = "${var.https_port}"
      protocol = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
      from_port = 0
      to_port = 0
      protocol = "-1"
      cidr_blocks = ["0.0.0.0/0"]
  }
}

variables.tf

variable "instance_type" {
  description = "The instance size to deploy. Defaults to t2.micro"
  default = "t2.micro"
}

variable "http_port" {
  description = "The port to use for HTTP traffic. Defaults to 80"
  default = "80"
}

variable "https_port" {
  description = "The port to use for HTTPS traffic. Defaults to 443"
  default = "443"
}



data "aws_ami" "ubuntu" {
    filter {
        name = "state"
        values = ["available"]
    }

    filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-*"]
  }

    filter {
        name   = "virtualization-type"
        values = ["hvm"]
    }

    owners = ["099720109477"]

}

locals {
  default_ami = "${data.aws_ami.ubuntu.id}"
}

variable aws_ami {
    description = "The AMI used to launch the instance. Defaults to Ubuntu 16.04"
    default = "${local.default_ami}"
}

3 个答案:

答案 0 :(得分:1)

尝试使用三元运算符插值:

variable "user_specified_ami" {
  default = "ami-12345678"
}

resource "aws_instance" "web" {
  ami = "${var.user_specified_ami == "" ? data.aws_ami.ubuntu.id : var.user_specified_ami}"
  # ... other params omitted ....
}

user_specified_ami的默认值设置为使用该AMI的值。将其设置为空白以使用从AWS提供商获取的AMI ID Terraform。

即如果user_specified_ami是其他空白(“”),则将为AMI选择它,否则AMI Terraform从AWS那里获得一个。

顺便说一句,也许您想在most_recent = true资源中使用data "aws_ami"参数?

答案 1 :(得分:0)

KJH的答案很好用,但是内嵌该逻辑对我来说有点混乱,因此我使用null_data_source进行了抽象。如下所示:

variable "ami" {
  default = ""
}

data "null_data_source" "data_variables" {
  inputs = {
    ami = "${var.ami == "" ? data.aws_ami.ubuntu.id : var.ami}"
  }
}

resource "aws_instance" "web" {
  ami = "${data.null_data_source.data_variables.outputs["ami"]}"
  # ... other params omitted ....
}

答案 2 :(得分:0)

与其他答案类似的解决方案,但使用coalesce function

variable "user_specified_ami" {
  default = ""
}

resource "aws_instance" "web" {
  ami = coalesce(var.user_specified_ami, data.aws_ami.ubuntu.id)
}