Terraform with aws to select ami 基于带排序的标签

Terraform with aws to select ami based on tag with sort

我正在构建一个 Terraform 配置,但遇到了一个棘手的问题 selection。我的 CI 构建 AMI,并根据 CI 上应用程序的当前构建在其上添加 MyVersionTag。我想select基于这个标签的AMI按版本排序(X.Y.Z格式)取最新的。

这是我使用 aws cli 到 select 我想使用的 AMI 的命令行:

aws ec2 describe-images --filters 'Name=tag-key,Values=MyVersionTag' --query 'reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId'

我正在寻找一种使用此 AMI ID 配置 EC2 实例的方法。我看到 2 种可能的方式(请纠正我):

有什么想法吗?

我最后做出来的是使用external关键字。这是我的解决方案:

# example.tf

resource "aws_instance" "my-instance" {
  ami = data.external.latest_ami.result.ImageId
  # Other config
}

data "external" "latest_ami" {
  program = ["sh", "latest_ami_id.sh"]
  # Or simply
  program = ["aws", "ec2", "describe-images", "--filters", "Name=tag-key,Values=MyVersionTag", "--query", "reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId"]
}

# latest_ami_id.sh

#!/bin/bash

# It returns a json with following keys :
#. ImageId, Description, Tags (version actually)
aws ec2 describe-images --filters "Name=tag-key,Values=SecretCore" --query 'reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId'

希望它能帮助别人。

我尝试使用你的命令,但出现错误,

Error: Unexpected External Program Results
│
│   with data.external.latest_ami,
│   on main.tf line 25, in data "external" "latest_ami":
│   25:   program = ["sh", "latest_ami.sh"]
│
│ The data source received unexpected results after executing the program.
│
│ Program output must be a JSON encoded map of string keys and string values.
│
│ If the error is unclear, the output can be viewed by enabling Terraform's logging at TRACE level. Terraform documentation on logging:
│ https://www.terraform.io/internals/debugging
│
│ Program: /usr/bin/sh
│ Result Error: json: cannot unmarshal string into Go value of type map[string]string

这是我的main.tf

resource "aws_instance" "web" {
  ami           = data.external.latest_ami.result.ImageId
  instance_type = "t3.micro"
}

data "external" "latest_ami" {
  program = ["sh", "latest_ami.sh"]
}

这是我的 latest_ami.sh

#latest_ami_id.sh
#!/bin/bash

# It returns a json with following keys :
#. ImageId, Description, Tags (version actually)
aws ec2 describe-images --filters 'Name=name,Values=packer-2022-04-06' --query 'reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId'

如果我尝试 运行 ./latest_ami.sh 就成功了

"ami-xxxxxxx"