Terraform - 在变量默认值中使用数据源输出

Luk*_*uke 4 terraform

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

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

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

我的模块如下:-

主文件

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"]
  }
}
Run Code Online (Sandbox Code Playgroud)

变量.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}"
}
Run Code Online (Sandbox Code Playgroud)

Fac*_*ano 6

与其他答案类似的解决方案,但使用合并函数

variable "user_specified_ami" {
  default = ""
}

resource "aws_instance" "web" {
  ami = coalesce(var.user_specified_ami, data.aws_ami.ubuntu.id)
}
Run Code Online (Sandbox Code Playgroud)


KJH*_*KJH 5

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

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 ....
}
Run Code Online (Sandbox Code Playgroud)

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

即如果user_specified_ami是任何其他空白(“”),那么它将被选择用于 AMI,否则 AMI Terraform 从 AWS 获取一个。

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