我们将最新批准的AMI存储在AWS参数存储中。使用Terraform创建新实例时,我想以编程方式获取此AMI ID。我有一个命令可以拉出AMI ID,但是我不确定如何在Terraform中使用它。
这是我用来提取AMI ID的命令:
$(aws ssm get-parameter --name /path/to/ami --query 'Parameter.Value' --output text)
这是我的Terraform脚本:
resource "aws_instance" "nginx" {
ami = "ami-c58c1dd3" # pull value from parameter store
instance_type = "t2.micro"
#key_name = "${var.key_name}"
provisioner "remote-exec" {
inline = [
"sudo yum install nginx -y",
"sudo service nginx start"
]
}
}
如何使用命令在Terraform脚本中提取AMI ID?
答案 0 :(得分:3)
您可以使用aws_ssm_parameter
data source在运行时获取参数值:
data "aws_ssm_parameter" "ami" {
name = "/path/to/ami"
}
resource "aws_instance" "nginx" {
ami = "${data.aws_ssm_parameter.ami.value}" # pull value from parameter store
instance_type = "t2.micro"
provisioner "remote-exec" {
inline = [
"sudo yum install nginx -y",
"sudo service nginx start"
]
}
}
但是,更好的方法可能是使用aws_ami
data source来更直接地过滤所需的AMI,而不是将AMI ID推送到SSM参数存储,然后在以后查找它。您可以过滤许多条件,包括名称,帐户所有者和标签。这是aws_instance
resource documentation中正在寻找最新的Ubuntu 14.04 AMI的示例:
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
resource "aws_instance" "web" {
ami = "${data.aws_ami.ubuntu.id}"
instance_type = "t2.micro"
tags = {
Name = "HelloWorld"
}
}