Last active
August 29, 2015 13:57
-
-
Save jdanbrown/9507370 to your computer and use it in GitHub Desktop.
ebs_set_names.py
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
#!/usr/bin/env python | |
# | |
# Set names on unnamed EBS volumes from their attached EC2 instance. | |
# | |
# Requires: | |
# - aws: https://github.com/aws/aws-cli (tested with aws-1.0.0) | |
# - jq: http://stedolan.github.io/jq/ (tested with jq-1.3) | |
import os, sys, json, subprocess | |
def show_cmd(cmd): | |
print '$', cmd | |
return cmd | |
def shell(cmd): | |
return subprocess.check_output(cmd, shell=True) | |
# This isn't set when we're run by cron [FIXME] | |
os.environ['AWS_CONFIG_FILE'] = '~/.awscli' | |
# (`aws` is actually easier to figure out than boto directly...) | |
instances = json.loads(shell(''' | |
aws ec2 describe-instances | jq ' | |
[ .Reservations[].Instances[] | { | |
key: .InstanceId, | |
value: { | |
Tags: (.Tags // {} | map(with_entries( | |
if .key == "Key" then .key = "key" elif .key == "Value" then .key = "value" else . end | |
)) | from_entries // {}) | |
} | |
} ] | from_entries | |
' | |
''')) | |
volumes = json.loads(shell(''' | |
aws ec2 describe-volumes | jq ' | |
[ .Volumes[] | { | |
key: .VolumeId, | |
value: { | |
InstanceId: ( | |
.VolumeId as $id | .Attachments | map(select(.VolumeId == $id and .State == "attached")) | .[0].InstanceId | |
), | |
Tags: (.Tags // {} | map(with_entries( | |
if .key == "Key" then .key = "key" elif .key == "Value" then .key = "value" else . end | |
)) | from_entries // {}) | |
} | |
} ] | from_entries | |
' | |
''')) | |
for v_id, v in sorted(volumes.items()): | |
if v['Tags'].get('Name'): | |
print '%s: Skipping, already named: %s' % (v_id, json.dumps(v['Tags']['Name'])) | |
elif not v.get('InstanceId'): | |
print '%s: No attached instance' % v_id | |
elif not instances.get(v['InstanceId']): | |
print '%s: Attached instance %s not found' % (v_id, v['InstanceId']) | |
elif not instances[v['InstanceId']]['Tags'].get('Name'): | |
print '%s: Attached instance %s has no name' % (v_id, v['InstanceId']) | |
else: | |
name = instances[v['InstanceId']]['Tags']['Name'] | |
print '%s: Setting name %s (from %s)' % (v_id, json.dumps(name), v['InstanceId']) | |
shell(show_cmd("aws ec2 create-tags --resources %s --tags Key=Name,Value='%s'" % ( | |
v_id, | |
name.replace(',', '\,').replace('=', '\='), | |
))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment