def backup(region_id='us-west-1'): '''This method searches for all EC2 instances with a tag of BackUp and creates a backup images of them then tags the images with a RemoveOn tag of a YYYYMMDD value of three UTC days from now ''' created_on = datetime.utcnow().strftime('%Y%m%d') remove_on = '20190513' # (datetime.utcnow() + timedelta(days=3)).strftime('%Y%m%d') session = awsutils.get_session(region_id) client = session.client('ec2') resource = session.resource('ec2') reservations = client.describe_instances(Filters=[{ 'Name': 'tag:RemoveOn', 'Values': [remove_on] }]) # pprint.pprint(reservations) images = [] for reservation in reservations['Reservations']: for instance_description in reservation['Instances']: if instance_description['State']['Name'] != 'running': continue instance_id = instance_description['InstanceId'] name = "InstanceId_{instance_id}_RemoveOn_{remove_on}".format( instance_id=instance_id, remove_on=remove_on) print("Creating Backup: {name}".format(name=name)) image_description = client.create_image(InstanceId=instance_id, Name=name) images.append(image_description['ImageId']) image = resource.Image(image_description['ImageId']) image.create_tags(Tags=[{ 'Key': 'RemoveOn', 'Value': remove_on }, { 'Key': 'Name', 'Value': name }])
def backup(region_id='us-east-1'): '''This method searches for all EC2 instances with a tag of BackUp and creates a backup images of them then tags the images with a RemoveOn tag of a YYYYMMDD value of three UTC days from now ''' created_on = datetime.utcnow().strftime('%Y%m%d') remove_on = (datetime.utcnow() + timedelta(days=3)).strftime('%Y%m%d') session = awsutils.get_session(region_id) client = session.client('ec2') resource = session.resource('ec2') reservations = client.describe_instances(Filters=[{ 'Name': 'tag-key', 'Values': ['BackUp'] }]) for reservation in reservations['Reservations']: for instance_description in reservation['Instances']: instance_id = instance_description['InstanceId'] name = f"InstanceId({instance_id})_CreatedOn({created_on})_RemoveOn({remove_on})" print(f"Creating Backup: {name}") image_description = client.create_image(InstanceId=instance_id, Name=name) images.append(image_description['ImageId']) image = resource.Image(image_description['ImageId']) image.create_tags(Tags=[{ 'Key': 'RemoveOn', 'Value': remove_on }, { 'Key': 'Name', 'Value': name }])
def get_session(region): return boto3.session.Session(region_name=region) session = awsutils.get_session('us-east-2') client = session.client('ec2') pprint.pprint(client.describe_instances()) demo = client.describe_instances(Filters=[{'Name': 'tag:Name', 'Values': ['my-instance']}]) pprint.pprint(demo)
def __init__(self, ec2_instance_name, key_path): session = awsutils.get_session('ap-northeast-2') self.client = session.client('ec2') self.ec2_instance_name = ec2_instance_name self.key_path = key_path self.__update_instance_data(ec2_instance_name) if self.ec2_instance_data['State']['Code'] != StatusCode.RUNNING and \ self.ec2_instance_data['State']['Code'] != StatusCode.STOPPED: pprint.pprint( 'Instance is stopping or staring. Try again after few seconds.' ) exit(100)
def cleanup(region_id='ap-south-1'): '''This method searches for all AMI images with a tag of RemoveOn and a value of YYYYMMDD of the day its ran on then removes it ''' today = datetime.utcnow().strftime('%Y%m%d') session = awsutils.get_session(region_id) client = session.client('ec2') resource = session.resource('ec2') images = client.describe_images(Filters=[{ 'Name': 'tag:RemoveOn', 'Values': [today] }]) for image_data in images['Images']: image = resource.Image(image_data['ImageId']) name_tag = [tag['Value'] for tag in image.tags if tag['Key'] == 'Name'] if name_tag: print("Deregistering {name_tag[0]}") image.deregister()
import boto3 import awsutils import pprint session = awsutils.get_session("us-west-2") client = session.client('sns') ''' Create a topic ''' response = client.create_topic(Name="test-topic") pprint.pprint(response) topic_arn = response['TopicArn'] pprint.pprint(topic_arn) # topic_arn = 'arn:aws:sns:us-west-2:507026312405:test-topic' ''' Create subsciprionts ''' # client.subscribe( # TopicArn=topic_arn, # Protocol='SMS', # Endpoint="+12088634367" # <-- number who'll receive an SMS message. # ) ''' Publish to a topic ''' # response = client.publish( # TopicArn=topic_arn, # Message='Hello World!', #)
#!/usr/bin/python import awsutils, ec2utils def get_client(): return session.client('emr') def get_meta_data(): return get_client() session = awsutils.get_session(ec2utils.get_meta_data().get('region'))
from datetime import datetime import pprint import awsutils instance_id = "i-0b25e4c5341c757a9" remove_on = '20190513' session = awsutils.get_session('us-west-1') client = session.client('ec2') demo = client.describe_instances() # demo = client.describe_instances(Filters=[{'Name': 'RemoveOn', # 'Values': [remove_on]}]) pprint.pprint(demo) instance_id = demo['Reservations'][0]['Instances'][0]['InstanceId'] print(instance_id) # stopped_instance = client.stop_instances(InstanceIds=[instance_id]) # pprint.pprint(stopped_instance) # started_instance = client.start_instances(InstanceIds=[instance_id]) # pprint.pprint(started_instance) ''' Alternate approach ''' # ec2 = session.resource('ec2')
import awsutils import pprint import boto3 session = awsutils.get_session('us-east-1') #client = session.client('ec2') #response = client.describe_instances( # InstanceIds=[ # 'i-0f82ea4e59ff0f349' # ] #) #print(response) ec2 = boto3.resource('ec2') for i in ec2.instances.all(): print(i.id) for vol in ec2.volumes.all(): #print(vol.id) volume4snip = vol.id print(volume4snip) result = ec2.create_snapshot(VolumeId=volume4snip, Description='Created by boto3') print(result.id)
import uuid import pprint import awsutils def create_bucket_name(bucket_prefix): # The generated bucket name must be between 3 and 63 chars long return ''.join([bucket_prefix, str(uuid.uuid4())]) def create_bucket(bucket_prefix, client, region): bucket_name = create_bucket_name(bucket_prefix) # print(bucket_name) bucket_response = client.create_bucket(Bucket=bucket_name, CreateBucketConfiguration={'LocationConstraint': region}) return bucket_name, bucket_response if __name__ == "__main__": region = "us-west-1" bucket_prefix = "aws-python-training-" session = awsutils.get_session(region) client = session.client('s3') bucket_name, bucket_response = create_bucket(bucket_prefix, client, region) print(bucket_name) pprint.pprint(bucket_response)