amazon-web-services - Terraform with aws to select ami based on tag with sort
问题描述
I'm building a Terraform config and I'm stuck with a tricky ami selection. My CI builds AMIs and add MyVersionTag
on it based on the current build of the app on the CI. I would like to select the AMI based on this tag sort by version (X.Y.Z
format) to take the latest.
Here is my command line using aws cli
to select the AMI I want to use:
aws ec2 describe-images --filters 'Name=tag-key,Values=MyVersionTag' --query 'reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId'
I'm searching a way to configure an EC2 instance with this AMI id. I see 2 possible ways (please correct me):
aws_instance
with pure AMI ID as text (result of a command line through variable)aws_ami
with filters
Any idea?
解决方案
我终于做的是使用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'
希望它会帮助别人。