Skip to content

Instantly share code, notes, and snippets.

@sarkis
Created December 4, 2018 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarkis/5fc9dab933334eb265da146747c1b220 to your computer and use it in GitHub Desktop.
Save sarkis/5fc9dab933334eb265da146747c1b220 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import boto3
import sys
import urllib.request
import subprocess
from glob import glob
from os.path import basename, dirname
def physical_drives():
drive_glob = '/sys/block/*/device'
return [basename(dirname(d)) for d in glob(drive_glob)]
def main():
ap = argparse.ArgumentParser(description="EBS attach and mount CLI")
vg = ap.add_mutually_exclusive_group(required=True)
vg.add_argument(
"-i",
"--volume-id",
help="volume id of the EBS volume to attach (required if volume name not specified)",
)
vg.add_argument(
"-n",
"--volume-name",
help="volume name of the EBS volume to attach (required if volume id not specified)",
)
ap.add_argument(
"-d",
"--device-id",
required=True,
help="device id to use when attaching EBS volume to instance (i.e. /dev/sdf)",
)
ap.add_argument(
"-m",
"--mount-dir",
required=True,
help="absolute path to directory where the newly attached volume will be mounted (i.e. /data)",
)
args = ap.parse_args()
ec2 = boto3.client('ec2')
# set volume_id
if args.volume_id is None:
resp = ec2.describe_volumes(
Filters=[
{
'Name': 'tag:Name',
'Values': [args.volume_name]
}
],
)
if len(resp['Volumes']) == 0:
print("No volumes found with Name: %s" % args.volume_name)
exit(-1)
elif len(resp['Volumes']) > 1:
print("Found more than 1 volume with the Name: %s" % args.volume_name)
exit(-1)
else:
args.volume_id = resp['Volumes'][0]['VolumeId']
pre_attach_drives = physical_drives()
# attach volume to instance
req = urllib.request.Request('http://169.254.169.254/latest/meta-data/instance-id')
with urllib.reqeust.urlopen(req) as res:
instance_id = res.read()
ec2.attach_volume(
VolumeId=args.volume_id,
InstanceId=instance_id,
Device=args.device_id,
)
ec2.get_waiter('volume_in_use').wait(
Filters=[
{
'Name': 'attachment.status',
'Values': ['attached'],
},
],
VolumeIds=[args.volume_id],
)
post_attach_drives = physical_drives()
# set local_device_id by diff of pre/post attach device list
new_device_list = list(set(pre_attach_drives).symmetric_difference(set(post_attach_drives)))
if len(new_device_list) != 1:
print("Error: %d new devices found, was expecting 1." % len(new_device_list))
exit(-1)
local_device_id = "/dev/" + new_device_list[0]
# mount using /usr/local/bin/mkfs-mount-ebs
p = subprocess.Popen(["mkfs-mount-ebs", local_device_id, args.mount_dir, "ext4"], stdout=subprocess.PIPE)
p.wait()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment