-
-
Save codeinthehole/ab9a8dc30917c5705846 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash | |
# | |
# Get the value of a tag for a running EC2 instance. | |
# | |
# This can be useful within bootstrapping scripts ("user-data"). | |
# | |
# Note the EC3 instance needs to have an IAM role that lets it read tags. The policy | |
# JSON for this looks like: | |
# | |
# { | |
# "Version": "2012-10-17", | |
# "Statement": [ | |
# { | |
# "Effect": "Allow", | |
# "Action": "ec2:DescribeTags", | |
# "Resource": "*" | |
# } | |
# ] | |
# } | |
# Define the tag you want to get the value for | |
KEY=bucket | |
# Install AWS CLI (you could just do 'apt-get install awscli' although you'll | |
# get an older version). | |
apt-get update | |
apt-get install -y python-pip | |
pip install -U pip | |
pip install awscli | |
# Grab instance ID and region as the 'describe-tags' action below requires them. Getting the region | |
# is a pain (see http://stackoverflow.com/questions/4249488/find-region-from-within-ec2-instance) | |
INSTANCE_ID=$(ec2metadata --instance-id) | |
REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep region | awk -F\" '{print $4}') | |
# Grab tag value | |
TAG_VALUE=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$KEY" --region=$REGION --output=text | cut -f5) |
@tinproject I did write that you "possibly" could, without testing. Looks like there is indeed no such thing as aws:ARN
, but there IS aws:SourceArn
that you could use (I didn't test it).
https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn
DescribeTags
action does not allow any Resource limitation (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-policy-keys ), the Policy Visual Editor image above also tells so.
Anyway, even if it supports resource limiting, a condition using aws:SourceArn
and ${ec2:SourceInstanceARN}
is always true in a petition from an Instance Role as both values will be the same, and as the documentation said you can not use ${ec2:SourceInstanceARN}
on the Resource
part of the policy, hence you're not limiting by resource.
Conclusion: don't lose time trying to make this work (as I already did)
There's an error getting the region.
You can fix it with
INSTANCE_ID=$(ec2-metadata --instance-id | awk '{print $2}')
TOOOOOOOOP
like a charm !!!!
If you know what Tag you are looking for you can query it directly like
--query 'Tags[?Key==`Name`].Value'
And yes those are backticks around the tag Key that you are looking for, in this cameName
.
Finally found the working syntax. Thanks @espoelstra
@kesor No, you can not restrict that action in an IAM policy...
