Last active
June 9, 2016 11:53
-
-
Save brillozon/188fde35d270382851c6 to your computer and use it in GitHub Desktop.
Loading EC2 instance and CFN stack metadata from AWS and into JSON files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
datadir=awsdata | |
instancedatafile=$datadir/instancedata.json | |
stackdatafile=$datadir/stack-metadata.json | |
# Put all the extracted data into one directory. | |
/bin/mkdir -p $datadir | |
curl="/usr/bin/curl --retry 3 --silent --show-error --fail" | |
instance_data_url=http://169.254.169.254/latest | |
# Use the HTTP reflection interface to determine which instance we are. | |
instanceid=$($curl $instance_data_url/meta-data/instance-id | /usr/bin/tee $datadir/instanceid) | |
# Use the AWS CLI to grab the instance data. | |
/usr/local/bin/aws ec2 describe-instances | | |
/usr/bin/jq '.Reservations[].Instances[] | select(.InstanceId == "'$instanceid'")' | | |
/usr/bin/tee $instancedatafile > /dev/null | |
# This is the pattern to extract data from the instance data JSON file. | |
zone=$(/usr/bin/jq '.Placement.AvailabilityZone' $instancedatafile) | |
stackid=$(/usr/bin/jq '.Tags[] | select(.Key == "aws:cloudformation:stack-id") | .Value' $instancedatafile) | |
logicalid=$(/usr/bin/jq '.Tags[] | select(.Key == "aws:cloudformation:logical-id") | .Value' $instancedatafile) | |
# Need the evals to remove the extra quoting. This assumes that the | |
# region is the availability zone with the last character truncated. | |
zlen=$(eval /bin/echo $zone | /usr/bin/wc -c) | |
rend=$(expr $zlen - 2) | |
region=$(eval /bin/echo $zone | /usr/bin/cut -c -$rend) | |
# Store off the region as it comes in handy and is not in the metadata. | |
/bin/echo $region > $datadir/region | |
# Be chatty. | |
/bin/echo | |
/bin/echo "Zone: $zone" | |
/bin/echo "Region: $region" | |
/bin/echo "Stack: $(eval echo $stackid)" | |
/bin/echo "Instance: $(eval echo $logicalid)" | |
/bin/echo | |
# cfn-get-metadata needs to run priviledged. | |
sudo /usr/local/bin/cfn-get-metadata -s $(eval echo $stackid) -r $(eval echo $logicalid) --region=$region | /usr/bin/tee $stackdatafile > /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment