地形 - 在变量默认中使用数据源输出



我正在创建一个模块来启动一个基本的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}"
}

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

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 的内容。将其设置为空白以使用 Terraform 从 AWS 提供商处获取的 AMI ID。

即,如果user_specified_ami是其他空白 ("(,则将为 AMI 选择它,否则 AMI Terraform 将从 AWS 获取一个。

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

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

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

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 ....
}

最新更新