I have an EC2 Image Builder which is triggered when an new version of a package is pushed to CodeArtifact. I would like to tag the resulting AMI with the version of the package that triggered the build. My goal is to add a tag that is meaningful to us than the unique build number created by the pipeline.
I see in the distribution settings how to set a tag with a constant value for the AMI. I don't see a way to update that value based on what triggered the the creation of the image in the first place.
I solved this same problem by adding a test component to the Image Build Pipeline that runs the following commands to tag the AMI during the testing phase. It wont work during the Build phases since the AMI is not created until the end of the build process so it has to the be ran in the testing phase.
phases:
- name: test
steps:
- name: tag-ami
action: ExecuteBash
inputs:
commands:
- sudo yum install jq -y
- cd /tmp
- aws codeartifact list-package-versions --region <Region> --domain <Domain> --domain-owner <AWS Owner Account Number> --repository <Repo Name> --format <Format> --namespace <NameSpace> --package <PackageName> >> tagpackage.json
- export version=$(cat tagpackage.json |jq -r .defaultDisplayVersion)
- hostname -i > privateip.txt
- export privateip=$(cat privateip.txt)
- instance_json=$(aws ec2 describe-instances --filters Name=private-ip-address,Values=$privateip)
- export instance_id=$(echo $instance_json | jq -r .Reservations[].Instances[].InstanceId)
- export imageid=$(aws ec2 describe-instances --instance-ids $instance_id --query 'Reservations[*].Instances[*].[ImageId]' --output text)
- aws ec2 create-tags --resources $imageid --tags Key=Version,Value=$version