Reputation: 984
I know I can access the tags via the metadata and cli tools, but is there anyway to access them whilst running cloud-init? Ideally I'd like to look for a tag called hostname and use it to set the machine host name.
Thanks
Upvotes: 3
Views: 1894
Reputation: 21
As mentioned in a previous answer by tgoodhart AWS has enabled the ability to get tags from the meta data store on an EC2 instance. However in order to have access to this, you will have to launch the EC2 instances with "InstanceMetadataTags" metadata option enabled. Otherwise the EC2 instance will not publish the tags to its meta data store and cloud init will not be able to read the tags. This link gives more information on how to enable this metadata option. https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#work-with-tags-in-IMDS
Upvotes: 1
Reputation: 3266
In more recent versions of cloud-init, metadata is available via jinja templates. EC2 also recently started exposing tags via the EC2 instance metadata store. Taken together, you can use this information to retrieve tags as part of your cloud-init.
Example:
cloud-init query -f "{{ds.meta_data.tags.instance}}"
As part of the user data:
## template: jinja
#cloud-config
final_message: |
My name is {{ds.meta_data.tags.instance.Name}}
Upvotes: 4
Reputation: 146
This command can be run from userdata (or any time, really) to access the instance ID from the metadata, and use it to pull the tag called "hostname". You could assign this to a variable, or use the output to directly set the hostname of the instance.
aws ec2 describe-instances --output text --query 'Reservations[*].Instances[*].Tags[?Key==`hostname`].Value' --instance-id `curl -s http://169.254.169.254/latest/meta-data/instance-id`
Upvotes: 2