Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
aws_asg_ebs_tagging/user-data/user_data.sh
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
31 lines (26 sloc)
1.23 KB
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 | |
# Get tags from the EC2 instance, | |
# and assign them to attached EBS volumes. | |
# | |
# Install required packages. | |
# This assumes Amazon Linux: | |
yum install -y aws-cli jq curl | |
echo Getting availability zone, region, and instance id... | |
EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone` | |
EC2_REGION=`echo "${EC2_AVAIL_ZONE:0:${#EC2_AVAIL_ZONE}-1}"` | |
EC2_INST_ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id` | |
echo Getting tags from this EC2 instance: ${EC2_INST_ID} | |
# The below jq command creates JSON usable by | |
# the aws ec2 create-tags command. | |
inst_tags_json=$(aws ec2 describe-tags --region ${EC2_REGION} --output json --filters Name=resource-id,Values=${EC2_INST_ID} | \ | |
jq '{ Tags: [ .Tags[] | select(.Key | test("^aws:"; "i") | not ) | {Key: .Key , Value: .Value} ] } ') | |
echo Getting volumes attached to this EC2 instance. . . | |
all_volume_ids=$(aws ec2 describe-volumes \ | |
--region ${EC2_REGION} \ | |
--output text \ | |
--filters Name=attachment.instance-id,Values=$EC2_INST_ID \ | |
--query 'Volumes[*].VolumeId') | |
echo "Tagging volumes $all_volume_ids with these tags: ${inst_tags_json}" | |
aws ec2 create-tags --region ${EC2_REGION} \ | |
--resources $all_volume_ids \ | |
--cli-input-json "${inst_tags_json}" | |