Terraform-从参数存储中获取值并传递给资源 [英] Terraform - Get a value from parameter store and pass to resource

查看:93
本文介绍了Terraform-从参数存储中获取值并传递给资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们将最新批准的AMI存储在AWS参数存储中.使用Terraform创建新实例时,我想以编程方式获取此AMI ID.我有一个命令可以拉出AMI ID,但不确定如何将其与Terraform一起使用.

We store our latest approved AMIs in AWS parameter store. When creating new instances with Terraform I would like to programatically get this AMI ID. I have a command to pull the AMI ID but I'm not sure how to use it with Terraform.

这是我用来提取AMI ID的命令:

Here is the command I use to pull the AMI ID:

$(aws ssm get-parameter --name /path/to/ami --query 'Parameter.Value' --output text)

这是我的Terraform脚本:

And here is my Terraform script:

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?

How can I use the command to pull the AMI ID in the Terraform script?

推荐答案

您可以使用 aws_ssm_parameter 数据源,以便在运行时获取参数值:

You can use the aws_ssm_parameter data source to fetch the value of a parameter at runtime:

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数据源来更直接地过滤所需的AMI,而不是将AMI ID推送到SSM参数存储中,然后在以后查找它.您可以过滤许多条件,包括姓名,帐户所有者和标签.这是 aws_instance 资源文档中的示例正在寻找最新的Ubuntu 14.04 AMI:

However, a better approach might be to use the aws_ami data source to filter for the AMI you want more directly instead of pushing the AMI ID to SSM parameter store and then looking it up later. You can filter on a number of criteria including name, account owner and tags. Here's the example from the aws_instance resource documentation that is looking for the latest 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"
  }
}

这篇关于Terraform-从参数存储中获取值并传递给资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆