Example #1
0
 def attach_sg_inbound_rule_http_rule(self, security_group_id):
     setup_cli_ec2(self.profile_name).authorize_security_group_ingress(
         CidrIp='0.0.0.0/0',
         FromPort=80,
         GroupId=security_group_id,
         IpProtocol='tcp',
         ToPort=80,
     )
     pprint(f"http rule attached to '{security_group_id}'.")
Example #2
0
def create_vpc(cidr, region_name='us-east-1'):
    try:
        response = setup_cli_ec2(region_name=region_name).create_vpc(
            CidrBlock=cidr,
            AmazonProvidedIpv6CidrBlock=False,
            #Ipv6Pool='string',
            #Ipv6CidrBlock='string',
            #DryRun=True | False,
            InstanceTenancy='default',
            #Ipv6CidrBlockNetworkBorderGroup='string',
            TagSpecifications=[
                {
                    'ResourceType': 'vpc',
                    'Tags': [
                        {
                            'Key': 'Name',
                            'Value': 'UAT1-VPC-boto3'
                        },
                    ]
                },
            ])
        pprint(response)
        variable['vpcid'] = response['Vpc']['VpcId']
        return response['Vpc']['VpcId']
    except Exception as e:
        print(e)
Example #3
0
def instance_status(id):
    instance_list = setup_cli_ec2().describe_instances(
        InstanceIds=id)['Reservations']
    for instance in instance_list:
        for each_instance in instance['Instances']:
            state = each_instance['State']['Name']
            return state
Example #4
0
def create_launch_template(region_name='us-east-1'):
    response = setup_cli_ec2(region_name=region_name).create_launch_template(
        LaunchTemplateName='Dev-instance-template-boto3',
        VersionDescription='01-boto3',
        LaunchTemplateData={
            'ImageId':
            'ami-0be2609ba883822ec',
            'InstanceType':
            't2.micro',
            'Monitoring': {
                'Enabled': False
            },
            'InstanceInitiatedShutdownBehavior':
            'terminate',
            'TagSpecifications': [
                {
                    'ResourceType': 'instance',
                    'Tags': [
                        {
                            'Key': 'Name',
                            'Value': 'Server-boto3'
                        },
                    ]
                },
            ],
            'SecurityGroupIds': [
                'sg-07d5ce1ffa7eff245',
            ],
        })
    pprint(response)
 def attach_ingress_rule_to_sg_with_cidr(self, sg_id, cidr, from_port,
                                         to_port, ip_protocol):
     try:
         response = setup_cli_ec2(
             self.profile_name).authorize_security_group_ingress(
                 GroupId=sg_id,
                 IpPermissions=[
                     {
                         'FromPort':
                         from_port,
                         'IpProtocol':
                         ip_protocol,
                         'IpRanges': [
                             {
                                 'CidrIp': cidr,
                                 'Description': 'boto3 rule'
                             },
                         ],
                         'ToPort':
                         to_port,
                     },
                 ],
             )
     except Exception as e:
         print(e)
Example #6
0
def create_subnet(vpcid):
    try:
        subnet_names = [
            'SubnetA-Public', 'SubnetB-Public', 'SubnetA-Private',
            'SubnetB-Private'
        ]
        cidrs = ['10.0.1.0/24', '10.0.2.0/24', '10.0.3.0/24', '10.0.4.0/24']
        az = ['us-east-1a', 'us-east-1b', 'us-east-1a', 'us-east-1b']

        for i in range(4):
            response = setup_cli_ec2().create_subnet(
                TagSpecifications=[
                    {
                        'ResourceType': 'subnet',
                        'Tags': [
                            {
                                'Key': 'Name',
                                'Value': subnet_names[i]
                            },
                        ]
                    },
                ],
                AvailabilityZone=az[i],
                #AvailabilityZoneId='string',
                CidrBlock=cidrs[i],
                VpcId=vpcid,
            )
            print("Subnet Created.....")
            variable[subnet_names[i]] = response['Subnet']['SubnetId']
            pprint(response)
    except Exception as e:
        print(e)
def list_all_ec2(region_name='us-east-1'):
    instance_list = setup_cli_ec2(
        region_name=region_name).describe_instances()['Reservations']
    count = 1
    for instance in instance_list:
        for each_instance in instance.get('Instances'):
            instance_id = each_instance.get('InstanceId'),
            image_id = each_instance.get('ImageId'),
            instance_type = each_instance.get('InstanceType')
            tags = each_instance.get('Tags')
            az = each_instance['Placement']['AvailabilityZone']
            state = each_instance['State']['Name']
            private_dns_name = each_instance.get('PrivateDnsName')
            sg = each_instance.get('SecurityGroups')
            launch_time = each_instance.get('LaunchTime').strftime("%d-%B-%Y")
            sg_name = ''
            for sg_grp in sg:
                sg_name = sg_grp.get('GroupName')

            for tag in tags:
                if tag['Key'] == "Name":
                    name = tag['Value']

            print(
                f"{count}. Instance Label: {name} | Instance ID: {instance_id[0]} | Instance Type: {instance_type} | "
                f"Image ID: {image_id[0]} | AZ: {az} | State: {state} | Private_DNS_Name: {private_dns_name} "
                f" | Launch Time: {launch_time} | {sg_name}")
            count += 1
Example #8
0
def ingress_rule(
    sg_id,
    from_port,
    ip_protocol,
    cidr,
    to_port,
    profile_name='pardeepsoni',
):

    response = setup_cli_ec2(profile_name).authorize_security_group_ingress(
        GroupId=sg_id,
        IpPermissions=[
            {
                'FromPort': from_port,
                'IpProtocol': ip_protocol,
                'IpRanges': [
                    {
                        'CidrIp': cidr,
                        'Description': 'boto3 rule'
                    },
                ],
                'ToPort': to_port,
            },
        ],
    )
    print("Rule attached to security group.")
Example #9
0
def attach_ig_to_vpc(vpc_id=variable.get('vpcid')):
    try:
        response = setup_cli_ec2().attach_internet_gateway(
            InternetGatewayId=variable.get('internet_gateway'), VpcId=vpc_id)
        print("Internet gateway attached")
    except Exception as e:
        print(e)
Example #10
0
def delete_internet_gateway():
    try:
        response = setup_cli_ec2().delete_internet_gateway(
            InternetGatewayId='igw-047ae58e7c697f174')
        print("Internet Gateway Deleted.")

    except Exception as e:
        print(e)
Example #11
0
def deattach_ig_from_vpc(vpc_id):
    try:
        response = setup_cli_ec2().detach_internet_gateway(
            InternetGatewayId='igw-047ae58e7c697f174', VpcId=vpc_id)
        print("Internet Gateway Deattach")

    except Exception as e:
        print(e)
Example #12
0
def modify_public_ip_auto_assign_subnet(subnet_id):
    response = setup_cli_ec2().modify_subnet_attribute(
        MapPublicIpOnLaunch={
            'Value': True,
        },
        SubnetId=subnet_id,
    )
    print(f"Enable the public Ip for the subnet {subnet_id}")
def describe_launch_template(lauch_template_id,
                             version_id,
                             region_name='us-east-1'):
    response = setup_cli_ec2(
        region_name=region_name).describe_launch_template_versions(
            LaunchTemplateId=lauch_template_id, Versions=[
                version_id,
            ])
    pprint(response)
Example #14
0
def associate_subnet_to_route_table(route_table_id, subnet_id):
    try:
        response = setup_cli_ec2().associate_route_table(
            RouteTableId=route_table_id,
            SubnetId=subnet_id,
        )
        print("Subnet is associated with the route table.")
    except Exception as e:
        print(e)
Example #15
0
def deattach_sg_inbound_rule_http_rule(security_group_id,
                                       region_name='us-east-1'):
    sg_rule = setup_cli_ec2(
        region_name=region_name).SecurityGroup(security_group_id)
    sg_rule.revoke_ingress(CidrIp='0.0.0.0/0',
                           FromPort=80,
                           IpProtocol='tcp',
                           ToPort=80)
    print(f"http rule revoked from '{security_group_id}'.")
Example #16
0
 def ec2_instance_delete(self):
     response = setup_cli_ec2(self.profile_name).describe_instances(
         Filters=[
             {
                 'Name': 'tag:Name',
                 'Values': [
                     'webapp-automation',
                 ],
                 'Name': 'instance-state-name',
                 'Values': [
                     'running',
                 ]
             },
         ], )
     for inst in response['Reservations']:
         for id in inst['Instances']:
             setup_cli_ec2(self.profile_name).terminate_instances(
                 InstanceIds=[id['InstanceId']])
             print(f"{id['InstanceId']} terminated ")
Example #17
0
def create_route_to_ig(ig=variable.get('internet_gateway'),
                       route_tableid=variable.get('PublicRouteTable')):
    try:
        response = setup_cli_ec2().create_route(
            DestinationCidrBlock='0.0.0.0/0',
            GatewayId=ig,
            RouteTableId=route_tableid,
        )
        print("internet route added to route table")
    except Exception as e:
        print(e)
def list_all_template(region_name='us-west-1'):
    launch_templates = setup_cli_ec2(
        region_name=region_name).describe_launch_templates()
    for each_template in launch_templates['LaunchTemplates']:
        launch_template_name = each_template['LaunchTemplateName']
        launch_template_id = each_template['LaunchTemplateId']
        default_version_number = each_template['DefaultVersionNumber']
        latest_version_number = each_template['LatestVersionNumber']
        create_time = each_template['CreateTime'].strftime('%d-%B-%Y')

        print(
            f"Launch Template Name: {launch_template_name} | Launch Template Id: {launch_template_id}"
            f"| Default Version Number: {default_version_number} | Latest Version Number: {latest_version_number} "
            f"| Create Time: {create_time}")
Example #19
0
def create_sg(sg_name, region_name='us-east-1'):
    response = setup_cli_ec2(region_name=region_name).create_security_group(
        Description='SSH Security Group Created by boto3',
        GroupName=sg_name,
        VpcId='vpc-4b1a1831',
        TagSpecifications=[{
            'ResourceType': 'security-group',
            'Tags': [
                {
                    'Key': 'Name',
                    'Value': 'SSH-boto3'
                },
            ]
        }])
    print(f"\nSecurity Group '{response.get('GroupId')}' is created")
    return response.get('GroupId')
Example #20
0
def attach_sg_inbound_rule_ssh_rule(security_group_id,
                                    region_name='us-east-1'):
    sg_rule = setup_cli_ec2(
        region_name=region_name).SecurityGroup(security_group_id)
    sg_rule.authorize_ingress(IpPermissions=[
        {
            'FromPort': 22,
            'IpProtocol': 'tcp',
            'IpRanges': [
                {
                    'CidrIp': '0.0.0.0/0',
                    'Description': 'SSH rule boto3'
                },
            ],
            'ToPort': 22,
        },
    ], )
    print(f"ssh rule attached to '{security_group_id}'.")
Example #21
0
 def create_sg(self, sg_name, region_name='us-east-1'):
     sg_response = setup_cli_ec2(
         self.profile_name, region_name=region_name).create_security_group(
             Description='webapp-security-group',
             GroupName=sg_name,
             VpcId='vpc-4b1a1831',
             TagSpecifications=[{
                 'ResourceType':
                 'security-group',
                 'Tags': [
                     {
                         'Key': 'Name',
                         'Value': 'webapp-automation'
                     },
                 ]
             }])
     print(f"\nSecurity Group '{sg_response.get('GroupId')}' is created")
     return sg_response.get('GroupId')
Example #22
0
    def create_launch_template(self, sg_id):
        message = '''#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd.service
systemctl enable httpd.service
cd /var/www/html/
wget https://html5up.net/paradigm-shift/download --no-check-certificate
unzip download
'''
        message_bytes = message.encode('"utf-8"')
        base64_bytes = base64.b64encode(message_bytes)
        base64_message = base64_bytes.decode('"utf-8"')
        response = setup_cli_ec2(self.profile_name).create_launch_template(
            LaunchTemplateName='webapp-lt',
            VersionDescription='01-boto3',
            LaunchTemplateData={
                'ImageId':
                'ami-0be2609ba883822ec',
                'InstanceType':
                't2.micro',
                'InstanceInitiatedShutdownBehavior':
                'terminate',
                'UserData':
                base64_message,
                'TagSpecifications': [
                    {
                        'ResourceType': 'instance',
                        'Tags': [
                            {
                                'Key': 'Name',
                                'Value': 'webapp-automation'
                            },
                        ]
                    },
                ],
                'SecurityGroupIds': [
                    sg_id,
                ],
            })
        pprint(response['LaunchTemplate'])
        lt_id = response['LaunchTemplate']['LaunchTemplateId']
        return lt_id
Example #23
0
def create_route_table(route_table_name='', vpc_id=variable.get('vpcid')):
    try:
        response = setup_cli_ec2().create_route_table(
            VpcId=vpc_id,
            TagSpecifications=[
                {
                    'ResourceType': 'route-table',
                    'Tags': [
                        {
                            'Key': 'Name',
                            'Value': route_table_name
                        },
                    ]
                },
            ])
        pprint(response)
        variable[route_table_name] = response['RouteTable']['RouteTableId']
    except Exception as e:
        print(e)
def list_all_sg(region_name='us-east-1'):
    response = setup_cli_ec2(
        region_name=region_name).describe_security_groups()
    count = 0
    for each_sg in response['SecurityGroups']:
        #print(each_sg.get('IpPermissions'))
        count += 1
        if each_sg.get('IpPermissions', 'null') == []:
            print(
                f"{count}. SG Name: {each_sg['GroupName']} | SG ID: {each_sg['GroupId']} | SG Description : '{each_sg.get('Description','None')}' | "
                f"From/To Port: null / null |  Protocol: 'null' | IP Range: ([], 'null')"
            )
        else:
            for ip_perm in each_sg.get('IpPermissions', 'null'):
                print(
                    f"{count}. SG Name: {each_sg['GroupName']} | SG ID: {each_sg['GroupId']} | SG Description : '{each_sg.get('Description','None')}' | "
                    f" From/To Port: {ip_perm.get('FromPort','null')} / {ip_perm.get('ToPort', 'null')} | "
                    f" Protocol: {ip_perm.get('IpProtocol','null')} | IP Range: {ip_perm.get('IpRanges'), 'null'}"
                )
Example #25
0
def create_internet_gateway():
    try:
        response = setup_cli_ec2().create_internet_gateway(TagSpecifications=[
            {
                'ResourceType': 'internet-gateway',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': 'InternetGateway-boto3'
                    },
                ]
            },
        ], )
        print("Internet Gateway Created...")
        pprint(response)
        variable['internet_gateway'] = response['InternetGateway'][
            'InternetGatewayId']
    except Exception as e:
        print(e)
Example #26
0
 def attach_ref_sgrule(self, security_group_id, refsg_name):
     response = setup_cli_ec2(
         self.profile_name).authorize_security_group_ingress(
             GroupId=security_group_id,
             IpPermissions=[
                 {
                     'FromPort':
                     80,
                     'IpProtocol':
                     'tcp',
                     'ToPort':
                     80,
                     'UserIdGroupPairs': [
                         {
                             'Description': f'traffic from {refsg_name}',
                             'GroupName': refsg_name,
                         },
                     ]
                 },
             ],
         )
     print(response)
Example #27
0
def ec2_operation():
    ec2_list = []
    while True:
        print("""\n=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=
        
1. Current state EC2 Instance.
2. Start EC2 Instance.
3. Stop EC2 Instance.
4. Reboot EC2 Instance.
5. Terminate EC2 Instance.
6. Switch to main menu.
7. Exit EC2 Service Console.

=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=x=
        """)
        try:
            option = int(input("Please enter your option (1-7): "))

            if option == 1:
                instance_id = input("Enter your instance ID: ")
                ec2_list.append(instance_id)
                state = instance_status(ec2_list)
                print(
                    f"\nEC2 instance '{instance_id}' is currently '{state}'.\n"
                )
                ec2_list = []

            elif option == 2:
                instance_id = input("Enter your instance ID: ")
                ec2_list.append(instance_id)
                state = instance_status(ec2_list)
                if state != 'running':
                    setup_cli_ec2().start_instances(InstanceIds=ec2_list)
                    print(f"\nStarting EC2 Instance '{instance_id}'\n")
                else:
                    print(
                        f"\n!!!!!!Cannot start the instance as instance '{instance_id}' is alaredy in running state.......\n'"
                    )
                ec2_list = []

            elif option == 3:
                instance_id = input("Enter your instance ID: ")
                ec2_list.append(instance_id)
                state = instance_status(ec2_list)
                if state == 'stopped':
                    print(
                        f"\n!!!!!!Cannot stop the instance as instance '{instance_id}' is alaredy in stopped state.......\n"
                    )
                else:
                    setup_cli_ec2().stop_instances(InstanceIds=ec2_list)
                    print(f"\nStopping EC2 Instance '{instance_id}'\n")
                ec2_list = []

            elif option == 4:
                instance_id = input("Enter your instance ID: ")
                ec2_list.append(instance_id)
                setup_cli_ec2().reboot_instances(InstanceIds=ec2_list)
                print(f"\nRebooting EC2 Instance '{instance_id}'\n")
                ec2_list = []

            elif option == 5:
                instance_id = input("Enter your instance ID: ")
                ec2_list.append(instance_id)
                setup_cli_ec2().terminate_instances(InstanceIds=ec2_list)
                print(f"\nTerminating EC2 Instance '{instance_id}'\n")
                ec2_list = []

            elif option == 6:
                break

            elif option == 7:
                print(f"\nThank you for using EC2 tool.")
                print("""
=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X= 


 ####### ##   ##  ######  ##    ##  ##  ##   ##    ##  #######  ##   ##
   ##    ##   ##  ##  ##  ## #  ##  ## ##     ##  ##   ##   ##  ##   ##
   ##    #######  ######  ##  # ##  ####        ##     ##   ##  ##   ## 
   ##    ##   ##  ##  ##  ##   ###  ## ##       ##     ##   ##  ##   ##
   ##    ##   ##  ##  ##  ##    ##  ##  ##      ##     #######  #######


   Pardeep Soni
=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=X=  

                                                        """)
                sys.exit()

            else:
                print(
                    "\nYour option is incorrect, please enter correct choice")

        except ValueError:
            print("\nYour option is incorrect, please enter correct choice\n")

        except Exception as e:
            print(f"\n!!!!!! {e}\n")
def delete_sg(security_group_id, region_name='us-east-1'):
    response = setup_cli_ec2(region_name=region_name).delete_security_group(
        GroupId=security_group_id, )
    print(f"Security Group '{security_group_id}' is deleted")
Example #29
0
def delete_vpc(vpcid):
    try:
        response = setup_cli_ec2().delete_vpc(VpcId=vpcid, )
        print(f" VPC '{vpcid}' Deleted..")
    except Exception as e:
        print(e)
Example #30
0
    def delete_sg(self, sg_id):
        response = setup_cli_ec2(self.profile_name, ).delete_security_group(
            GroupId=sg_id, )

        print("Security Group Deleted")