def request_spot(name, bid, **kwargs): assert name not in instances() spec = instance_spec(**kwargs) spec['UserData'] = base64.b64encode(spec['UserData'].encode()).decode() requests = ec2().meta.client.request_spot_instances( InstanceCount=1, SpotPrice=str(bid), LaunchSpecification=spec) request_ids = [r['SpotInstanceRequestId'] for r in requests['SpotInstanceRequests']] while True: try: desc = ec2().meta.client.describe_spot_instance_requests(SpotInstanceRequestIds=request_ids) states = [d['Status']['Code'] for d in desc['SpotInstanceRequests']] log.info('States: {}'.format(', '.join(states))) if all([s == 'fulfilled' for s in states]): break except boto3.exceptions.botocore.client.ClientError: log.info(f'Exception while waiting for spot requests') raise time.sleep(5) instance = ec2().Instance(desc['SpotInstanceRequests'][0]['InstanceId']) set_name(instance, name) return instance
def aws_menu(): while True: os.system("clear") accessories.figlet("AWS Menu", "starwars", 3) os.system("tput bold") os.system("tput setaf 2") print(""" Which service you want to use ?\n [1] : Install AWS CLI [2] : Configure AWS CLI with your AWS account [3] : EC2 [4] : EBS [5] : S3 [6] : Return to Main Menu [7] : Exit """) os.system("tput sgr 0") opt_4 = int(input("Enter your choice : ")) if opt_4 == 1: os.system(""" if ls /usr/local | grep aws-cli > /dev/null then echo 'AWS CLI is already installed' else echo 'Installing AWS CLI......' curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" > /dev/null unzip awscliv2.zip > /dev/null sudo ./aws/install > /dev/null if aws --version | grep aws then echo 'AWS CLI is successfully installed' else echo 'Could not able to install AWS CLI' fi fi """) accessories.wait() elif opt_4 == 2: print( "Note : To configure AWS CLI you need to have an IAM user created in your AWS account" ) opt_4_1 = input("Enter your IAM user profile name :- ") print("Enter your IAM user credentials and details below") os.system("aws configure") print("AWS CLI configured to use for {} user".format(opt_4_1)) accessories.wait() elif opt_4 == 3: aws.ec2() elif opt_4 == 4: aws.ebs() elif opt_4 == 5: aws.s3() elif opt_4 == 6: break elif opt_4 == 7: exit() else: print("Invalid choice!!!") accessories.wait()
def create_instance(name, **kwargs): assert name not in instances() spec = instance_spec(**kwargs) instance = ec2().create_instances(MinCount=1, MaxCount=1, **spec)[0] set_name(instance, name) return instance
def create_image(instance, name='python-ec2'): if name in images(): log.warn('Deleting old image') im = images()[name] devices = im.block_device_mappings im.deregister() for device in devices: ec2().Snapshot(device['Ebs']['SnapshotId']).delete() im = instance.create_image(Name=name, NoReboot=False) while True: im = ec2().Image(im.id) log.info(f'Image is {im.state}') if im.state == 'available': return im time.sleep(5)
def aws_conn(id): """create a connection to the EC2 machine and return the handle""" global user check_user_var() uid = users(user=user).id creds = db(db.aws_creds.uid==uid).select().first() account_id = creds['account_id'] secret = creds['secret'] key = creds['key'] instances = db(db.aws_instances.id==id).select().first() instance = instances['instance'] region = instances['region'] rate = instances['rate'] if not rate: rate = 0.0 return awsmod.ec2(key,secret,account_id,instance,region,rate)
def instances(): return {as_dict(i.tags).get('Name', 'unnamed'): i for i in ec2().instances.all() if i.state['Name'] != 'terminated'}
def set_name(obj, name): ec2().create_tags(Resources=[obj.id], Tags=[{'Key': 'Name', 'Value': name}])
def images(): return {i.name: i for i in ec2().images.filter(Owners=['self']).all()}
def create_volume(name, size): assert name not in volumes(), 'Already created a volume with that name' assert size < 128 volume = ec2().create_volume(AvailabilityZone=config('AVAILABILITY_ZONE'), Size=size) set_name(volume, name) return volume
def volumes(): return {as_dict(i.tags).get('Name', 'unnamed'): i for i in ec2().volumes.all()}