Best Python code snippet using localstack_python
2017-12-05-aws_machine.py
Source:2017-12-05-aws_machine.py  
1#  ------------------------------------------------------------------------ # 2#                                                                           # 3#                     libraries                                             # 4#                                                                           # 5#  ------------------------------------------------------------------------ # 6import sys7import boto38from botocore.exceptions import ClientError9#  ------------------------------------------------------------------------ #10#                                                                           # 11#                     constants                                             # 12#                                                                           # 13#  ------------------------------------------------------------------------ # 14g_profile = 'us-east'            # profiles: au | us-east | eu15g_instance_type = 'm4.large'16ami = 'ami-31ecfb26'             # only in us-east-1, virginia17# Fixed constansts18g_name = 'fast-ai'19g_cidr = '0.0.0/0'20g_cidr_block = '10.0.0.0/28'21# --- Create22#  ------------------------------------------------------------------------ # 23#                                                                           # 24#                     Create VPC                                            # 25#                                                                           # 26#  ------------------------------------------------------------------------ # 27def create_vpc(p_ec2_resource, p_ec2_client):28    """29    Create a Virtual Private Channel (VPC)30    Add a tag, even though I cannot see the tag later.... <sigh>31    Enable DNS32    Enable Hostname support33    Return the ID.34    """35    36    l_vpc_id = p_ec2_resource.create_vpc(CidrBlock=g_cidr_block)37    l_vpc_id.create_tags(Tags=[{"Key": "VPCName", "Value": g_name}])38    print('----------')39    print(l_vpc_id.id)40    # int(l_vpc_id['id'])41    print('----------')42    # ec2_client.modify_vpc_attribute(VpcId=l_vpc_id.id, EnableDnsSupport={'Value': True})43    # ec2_client.modify_vpc_attribute(VpcId=l_vpc_id.id, EnableDnsHostnames={'Value': True})44    45    print('Creating...please wait')46    l_vpc_id.wait_until_available()47    print('Complete')48    print(l_vpc_id)49    50    return l_vpc_id51        52#  ------------------------------------------------------------------------ # 53#                                                                           # 54#                     Create Internet Gateway                               # 55#                                                                           # 56#  ------------------------------------------------------------------------ # 57def create_gateway(p_ec2_resource, p_vpc_id):58    """59    Create an Internet Gateway60    Add a tag, still do not understand tags <bigger sigh>61    return ID62    """63    64    l_ig = p_ec2_resource.create_internet_gateway()65    print('my ig = {}'.format(l_ig))66    l_ig.attach_to_vpc(VpcId=p_vpc_id)67    return l_ig68    69# ec2_client.modify_vpc_attribute(VpcId=my_vpc['Vpc']['VpcId'], EnableDnsSupport={'Value':True})70# ec2_client.modify_vpc_attribute(VpcId=my_vpc['Vpc']['VpcId'], EnableDnsHostnames={'Value':True})    71# Create an Internet Gateway72# export internetGatewayId=$(aws ec2 create-internet-gateway --query 'InternetGateway.InternetGatewayId' 73#                              --output text)74# aws ec2 create-tags --resources $internetGatewayId --tags --tags Key=Name,Value=$name-gateway75# aws ec2 attach-internet-gateway --internet-gateway-id $internetGatewayId --vpc-id $vpcId76    77# --- deletes   78#  ------------------------------------------------------------------------ # 79#                                                                           # 80#                     detach internet gateway                               # 81#                                                                           # 82#  ------------------------------------------------------------------------ # 83    84def detach_internet_gateway(p_ig, p_ig_id):85    """86    Detach the Internet Gateway from the VPC87    If it fails with Client Error of not attached, it should be OK88        verify error is 89           'ClientError: An error occurred (Gateway.NotAttached) when calling the 90           DetachInternetGateway operation: resource igw-8f4bc9f6 is not 91           attached to network igw-8f4bc9f6'92    """93    command_status = False94    95    try:96        l_response = p_ig.detach_from_vpc(VpcId = p_ig_id)97        98        print(l_response)99        command_status = True100        101    except ClientError as e:102        if e.response['Error']['Code'] == 'Gateway.NotAttached':103            # This error is ok.104            command_status = True105    106    return command_status107#  ------------------------------------------------------------------------ # 108#                                                                           # 109#                     delete internet gateway                               # 110#                                                                           # 111#  ------------------------------------------------------------------------ # 112    113def delete_internet_gateway(p_ig, p_ig_id):114    """115    delete the Internet Gateway from the VPC116    If it fails with Client Error, NOT OK117        verify error is 118           'ClientError: An error occurred (DependencyViolation) when calling 119           the DeleteInternetGateway operation: The internetGateway 'igw-8f4bc9f6' 120           has dependencies and cannot be deleted.121    """122    command_status = False123    124    try:125        l_response = p_ig.delete()126        print(l_response)127        command_status = True128        129    except ClientError as e:130        if e.response['Error']['Code'] == 'DependencyViolation':131            command_status = False132            # This error is NOT ok.133            print("Unable to delete internet gateway due to a dependency violation")134            print('error text: {}'.format(e))135        else:136            command_status = False            137            print('Unknown Error when deleting Internet Gateway {}'.format(e.response['Error']['Code']) )138            print('error text: {}'.format(e))139            140    return command_status    141#  ------------------------------------------------------------------------ # 142#                                                                           # 143#                     delete security group                                 # 144#                                                                           # 145#  ------------------------------------------------------------------------ # 146    147def delete_security_group(p_sg, p_sg_id):148    """149    delete the security group from the VPC150    """151    command_status = False152    153    try:154        l_response = p_sg.delete()155        delete_result = l_response['ResponseMetadata']['HTTPStatusCode']156        if delete_result == 200:157            command_status = True158        else:159            print('ERROR: Failed to delete security for unknown reasons, error not raised')160            print(l_response)161            print('-----------------------------------------------------')162            command_status = False163        164    except ClientError as e:165        if e.response['Error']['Code'] == 'DependencyViolation':166            command_status = False167            # This error is NOT ok.168            print("Unable to delete security group due to a dependency violation")169            print('error text: {}'.format(e))170        else:171            command_status = False            172            print('Unknown Error when deleting Security Group {}'.format(e.response['Error']['Code']) )173            print('error text: {}'.format(e))174            175    return command_status    176#  ------------------------------------------------------------------------ # 177#                                                                           # 178#                     delete subnet                                         # 179#                                                                           # 180#  ------------------------------------------------------------------------ # 181    182def delete_subnet(p_subnet, p_subnet_id):183    """184    delete the subnet from the VPC185    """186    command_status = False187    188    try:189        l_response = p_subnet.delete()190        delete_result = l_response['ResponseMetadata']['HTTPStatusCode']191        if delete_result == 200:192            command_status = True193        else:194            print('ERROR: Failed to delete subnet for unknown reasons, error not raised')195            print(l_response)196            print('-----------------------------------------------------')197            command_status = False198        199    except ClientError as e:200        if e.response['Error']['Code'] == 'DependencyViolation':201            command_status = False202            # This error is NOT ok.203            print("Unable to delete subnet due to a dependency violation")204            print('error text: {}'.format(e))205        else:206            command_status = False            207            print('Unknown Error when deleting subnet {}'.format(e.response['Error']['Code']) )208            print('error text: {}'.format(e))209            210    return command_status    211     212# --- remove components213#  ------------------------------------------------------------------------ # 214#                                                                           # 215#                     Remove vpc network acls                               # 216#                                                                           # 217#  ------------------------------------------------------------------------ # 218def remove_vpc_network_acls(p_ec2_resource, p_vpc_id, p_level):   219    """220    Remove all subnets for this vpc221    """222    p_level += 4223 224    overall_success = True225    overall_success = False226    227    228    for subnet in p_ec2_resource.meta.client.describe_network_acls()['SecurityGroups']:229        230        l_subnet_id = subnet['GroupId']231        l_vpc_owner_id = subnet['VpcId'] 232        l_subnet = p_ec2_resource.SecurityGroup(l_sg_id)233        234        if l_vpc_owner_id != p_vpc_id.id:235            print('{} Security Group VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_sg_id, l_vpc_owner_id))236            continue237        238        print('{} Security Group {}, owner VPC {}'.format(' '*p_level, l_sg_id, l_vpc_owner_id))239        if not delete_security_group(l_sg, l_sg_id):240            overall_success = False241        else:242            print('{}     security group deleted'.format(' '*p_level))    243            244    p_level -= 4245    return overall_success        246#  ------------------------------------------------------------------------ # 247#                                                                           # 248#                     Remove vpc vpn attachments                            # 249#                                                                           # 250#  ------------------------------------------------------------------------ # 251def remove_vpc_vpn_attachments(p_ec2_resource, p_vpc_id, p_level):  252    """253    Remove all subnets for this vpc254    """255    p_level += 4256 257    overall_success = True258    overall_success = False259    260    261    for subnet in p_ec2_resource.meta.client.describe_vpn_gateways()['SecurityGroups']:262        263        l_subnet_id = subnet['GroupId']264        l_vpc_owner_id = subnet['VpcId'] 265        l_subnet = p_ec2_resource.SecurityGroup(l_sg_id)266        267        if l_vpc_owner_id != p_vpc_id.id:268            print('{} Security Group VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_sg_id, l_vpc_owner_id))269            continue270        271        print('{} Security Group {}, owner VPC {}'.format(' '*p_level, l_sg_id, l_vpc_owner_id))272        if not delete_security_group(l_sg, l_sg_id):273            overall_success = False274        else:275            print('{}     security group deleted'.format(' '*p_level))    276            277    p_level -= 4278    return overall_success        279        280#  ------------------------------------------------------------------------ # 281#                                                                           # 282#                     Remove vpc route tables                                # 283#                                                                           # 284#  ------------------------------------------------------------------------ # 285                286def remove_vpc_route_tables(p_ec2_resource, p_vpc_id, p_level):   287    """288    Remove all subnets for this vpc289    """290    p_level += 4291 292    overall_success = True293    overall_success = False294    295    296    for subnet in p_ec2_resource.meta.client.describe_route_tables()['SecurityGroups']:297        298        l_subnet_id = subnet['GroupId']299        l_vpc_owner_id = subnet['VpcId'] 300        l_subnet = p_ec2_resource.SecurityGroup(l_sg_id)301        302        if l_vpc_owner_id != p_vpc_id.id:303            print('{} Security Group VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_sg_id, l_vpc_owner_id))304            continue305        306        print('{} Security Group {}, owner VPC {}'.format(' '*p_level, l_sg_id, l_vpc_owner_id))307        if not delete_security_group(l_sg, l_sg_id):308            overall_success = False309        else:310            print('{}     security group deleted'.format(' '*p_level))    311            312    p_level -= 4313    return overall_success        314                    315#  ------------------------------------------------------------------------ # 316#                                                                           # 317#                     Remove vpc network interfaces                         # 318#                                                                           # 319#  ------------------------------------------------------------------------ # 320def remove_vpc_network_interfaces(p_ec2_resource, p_vpc_id, p_level): 321    """322    Remove all subnets for this vpc323    """324    p_level += 4325 326    overall_success = True327    overall_success = False328    329    330    for subnet in p_ec2_resource.meta.client.describe_network_interfaces()['SecurityGroups']:331        332        l_subnet_id = subnet['GroupId']333        l_vpc_owner_id = subnet['VpcId'] 334        l_subnet = p_ec2_resource.SecurityGroup(l_sg_id)335        336        if l_vpc_owner_id != p_vpc_id.id:337            print('{} Security Group VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_sg_id, l_vpc_owner_id))338            continue339        340        print('{} Security Group {}, owner VPC {}'.format(' '*p_level, l_sg_id, l_vpc_owner_id))341        if not delete_security_group(l_sg, l_sg_id):342            overall_success = False343        else:344            print('{}     security group deleted'.format(' '*p_level))    345            346    p_level -= 4347    return overall_success        348    349                350#  ------------------------------------------------------------------------ # 351#                                                                           # 352#                     Remove vpc peering connections                        # 353#                                                                           # 354#  ------------------------------------------------------------------------ # 355def remove_vpc_peering_connections(p_ec2_resource, p_vpc_id, p_level):  356    """357    Remove all subnets for this vpc358    """359    p_level += 4360 361    overall_success = True362    overall_success = False363    364    365    for subnet in p_ec2_resource.meta.client.describe_vpc_peering_connections()['SecurityGroups']:366        367        l_subnet_id = subnet['GroupId']368        l_vpc_owner_id = subnet['VpcId'] 369        l_subnet = p_ec2_resource.SecurityGroup(l_sg_id)370        371        if l_vpc_owner_id != p_vpc_id.id:372            print('{} Security Group VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_sg_id, l_vpc_owner_id))373            continue374        375        print('{} Security Group {}, owner VPC {}'.format(' '*p_level, l_sg_id, l_vpc_owner_id))376        if not delete_security_group(l_sg, l_sg_id):377            overall_success = False378        else:379            print('{}     security group deleted'.format(' '*p_level))    380            381    p_level -= 4382    return overall_success        383        384#  ------------------------------------------------------------------------ # 385#                                                                           # 386#                     Remove vpc vpn connections                            # 387#                                                                           # 388#  ------------------------------------------------------------------------ # 389                390def remove_vpc_vpn_connection(p_ec2_resource, p_vpc_id, p_level): 391    """392    Remove all subnets for this vpc393    """394    p_level += 4395 396    overall_success = True397    overall_success = False398    399    400    for vpn in p_ec2_resource.meta.client.describe_vpn_connections()['SecurityGroups']:401        402        l_subnet_id = subnet['GroupId']403        l_vpc_owner_id = subnet['VpcId'] 404        l_subnet = p_ec2_resource.SecurityGroup(l_sg_id)405        406        if l_vpc_owner_id != p_vpc_id.id:407            print('{} Security Group VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_sg_id, l_vpc_owner_id))408            continue409        410        print('{} Security Group {}, owner VPC {}'.format(' '*p_level, l_sg_id, l_vpc_owner_id))411        if not delete_security_group(l_sg, l_sg_id):412            overall_success = False413        else:414            print('{}     security group deleted'.format(' '*p_level))    415            416    p_level -= 4417    return overall_success        418        419#  ------------------------------------------------------------------------ # 420#                                                                           # 421#                     Remove vpc subnet                                     # 422#                                                                           # 423#  ------------------------------------------------------------------------ # 424def remove_vpc_subnets(p_ec2_resource, p_vpc_id, p_level):     425    """426    Remove all subnets for this vpc427    """428    p_level += 4429 430    overall_success = True431    overall_success = False432    433    for subnet in p_ec2_resource.meta.client.describe_subnets()['Subnets']:434        l_vpc_owner_id = subnet['VpcId'] 435        l_subnet_id = subnet['SubnetId']436        l_subnet = p_ec2_resource.SecurityGroup(l_subnet_id)437        if l_vpc_owner_id != p_vpc_id.id:438            print('{} subnet VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_subnet_id, l_vpc_owner_id))439            continue440        441        442        print('{} subnet {}, owner VPC {}'.format(' '*p_level, l_subnet_id, l_vpc_owner_id))443        if not delete_subnet(l_subnet, l_subnet_id):444            overall_success = False445        else:446            print('{}     subnet deleted'.format(' '*p_level))    447            448    p_level -= 4449    return overall_success        450    451#  ------------------------------------------------------------------------ # 452#                                                                           # 453#                     Remove vpc security group                             # 454#                                                                           # 455#  ------------------------------------------------------------------------ # 456def remove_vpc_security_group(p_ec2_resource, p_vpc_id, p_level):     457    """458    Remove all security groups for this vpc459    """460    p_level += 4461 462    overall_success = True463    overall_success = False464    465    466    for sg in p_ec2_resource.meta.client.describe_security_groups()['SecurityGroups']:467        468        l_sg_id = sg['GroupId']469        l_vpc_owner_id = sg['VpcId'] 470        l_sg = p_ec2_resource.SecurityGroup(l_sg_id)471        472        if l_vpc_owner_id != p_vpc_id.id:473            print('{} Security Group VPC {}, owner VPC {} - skip, wrong VPC'.format(' '*p_level, l_sg_id, l_vpc_owner_id))474            continue475        476        print('{} Security Group {}, owner VPC {}'.format(' '*p_level, l_sg_id, l_vpc_owner_id))477        if not delete_security_group(l_sg, l_sg_id):478            overall_success = False479        else:480            print('{}     security group deleted'.format(' '*p_level))    481            482    p_level -= 4483    return overall_success        484#  ------------------------------------------------------------------------ # 485#                                                                           # 486#                     Remove Internet Gateway                               # 487#                                                                           # 488#  ------------------------------------------------------------------------ # 489def remove_vpc_internet_gateway(p_ec2_resource, p_vpc_id, p_level):     490    """491    Remove all Internet Gateways...492    dunno about the default, is there one?493    Bugger it, just remove em all....494    """495    496    p_level += 4497 498    overall_success = True499    500    for ig in p_ec2_resource.meta.client.describe_internet_gateways()['InternetGateways']:501        502        l_ig_id = ig['InternetGatewayId']503        504        # This gateway can be attached to multiple VPC505        # Loop through each attachment, and see if attached to this VPC at all.506        is_attached_to_vpc = False  507        is_attached_count = 0508        509        for att in ig['Attachments']:510            is_attached_count += 1511            l_vpc_owner_id = att['VpcId']512            if l_vpc_owner_id != p_vpc_id.id:513                is_attached_to_vpc = True514         515        if not is_attached_to_vpc:516            print('{} internet gateway not attached to this VPC - skip'.format(' '*p_level))517            continue518 519        l_ig = p_ec2_resource.InternetGateway(l_ig_id)520        print('{} Process removal internet gateway : {}'.format(' ' * p_level, l_ig_id))521        p_level += 4522        if not detach_internet_gateway(l_ig, l_ig_id):523            print('{} internet gateway failed to detach '.format(' '*p_level))    524            overall_success = False525        else:526            print('{} internet gateway detached'.format(' '*p_level))    527            is_attached_count -= 1528          529        # Test to see if attached to any other VPC, if not, then delete.530        if is_attached_count == 0:             531            if not delete_internet_gateway(l_ig, l_ig_id):532                print('{} internet gateway failed to delete '.format(' '*p_level))    533                overall_success = False534            else:535                print('{} internet gateway deleted'.format(' '*p_level))    536        537        p_level -= 4538        539    p_level -= 4540    return overall_success        541    542# --- remove VPC543#  ------------------------------------------------------------------------ # 544#                                                                           # 545#                     Remove VPC                                            # 546#                                                                           # 547#  ------------------------------------------------------------------------ # 548def remove_all_vpc(p_ec2_resource):549    """550    Remove all VPC551    except for default552    553    This will start failing where there are dependencies....will have to fix that later!554    """555    level = 0556    print('Start process - Remove all VPC except default')557    for r in p_ec2_resource.meta.client.describe_vpcs()[ 'Vpcs']:558        level += 4559        560        l_vpc_default = r['IsDefault']561        l_vpc_id = r['VpcId']562        563        vpc_ready_for_delete = True564        565        if l_vpc_default:566            print('    vpc id {}: is default, not removing'.format(l_vpc_id))567        else:568            print('    vpc id {}: prepare for delete'.format(l_vpc_id))569            570            l_vpc = p_ec2_resource.Vpc(id = l_vpc_id)571            if l_vpc.tags is not None:572                for tag in l_vpc.tags:573                    print('{} vpc tags: : {} {}'.format(' '*level * 2, tag['Key'], tag['Value']))574            575            if not remove_vpc_security_group(p_ec2_resource, l_vpc, level):576                vpc_ready_for_delete = False577            578            if not remove_vpc_subnets(p_ec2_resource, l_vpc, level):579                vpc_ready_for_delete = False580            581            if not remove_vpc_network_acls(p_ec2_resource, l_vpc, level):582                vpc_ready_for_delete = False583                584# =============================================================================585#             if not remove_vpc_vpn_attachments(p_ec2_resource, l_vpc, level):586#                 vpc_ready_for_delete = False587#                 588#             if not remove_vpc_route_tables(p_ec2_resource, l_vpc, level):589#                 vpc_ready_for_delete = False590#                 591#             if not remove_vpc_network_interfaces(p_ec2_resource, l_vpc, level):592#                 vpc_ready_for_delete = False593#                 594#             if not remove_vpc_vpc_peering_connections(p_ec2_resource, l_vpc, level):595#                 vpc_ready_for_delete = False596#                 597#             if not remove_vpc_vpn_connection(p_ec2_resource, l_vpc, level):598#                 vpc_ready_for_delete = False599#             600#             if not remove_vpc_internet_gateway(p_ec2_resource, l_vpc, level):601#                 vpc_ready_for_delete = False602# =============================================================================603            if vpc_ready_for_delete:604                l_vpc.delete()605            else:606                print('{} VPC not ready for delete...bugger'.format(' '*level))607            608# =============================================================================609#                610# Possible dependencies611# ---------------------612# DONE Security Group613# DONE Internet Gateways614#615# Subnets616# Network ACLs617# VPN Attachments618# Route Tables619# Network Interfaces620# VPC Peering Connections621# vpn-connection. 622#             623# =============================================================================624# =============================================================================625#                dir(p_ec2_resource.meta.client)626#                627#  u'describe_subnets',628#                629#  u'describe_network_acls',630#631#  u'describe_vpn_gateways',            632#633#  u'describe_route_tables',634#635#  u'describe_network_interfaces',636#637#  u'describe_vpc_peering_connections',638#639#  u'describe_vpn_connections',640# ---------------------------------                641#  u'describe_account_attributes',642#  u'describe_addresses',643#  u'describe_availability_zones',644#  u'describe_bundle_tasks',645#  u'describe_classic_link_instances',646#  u'describe_conversion_tasks',647#  u'describe_customer_gateways',648#  u'describe_dhcp_options',649#  u'describe_egress_only_internet_gateways',650#  u'describe_export_tasks',651#  u'describe_flow_logs',652#  u'describe_fpga_images',653#  u'describe_host_reservation_offerings',654#  u'describe_host_reservations',655#  u'describe_hosts',656#  u'describe_iam_instance_profile_associations',657#  u'describe_id_format',658#  u'describe_identity_id_format',659#  u'describe_image_attribute',660#  u'describe_images',661#  u'describe_import_image_tasks',662#  u'describe_import_snapshot_tasks',663#  u'describe_instance_attribute',664#  u'describe_instance_status',665#  u'describe_instances',666#  u'describe_internet_gateways',667#  u'describe_key_pairs',668#  u'describe_moving_addresses',669#  u'describe_nat_gateways',670#  u'describe_network_interface_attribute',671#  u'describe_network_interface_permissions',672#  u'describe_placement_groups',673#  u'describe_prefix_lists',674#  u'describe_regions',675#  u'describe_reserved_instances',676#  u'describe_reserved_instances_listings',677#  u'describe_reserved_instances_modifications',678#  u'describe_reserved_instances_offerings',679#  u'describe_scheduled_instance_availability',680#  u'describe_scheduled_instances',681#  u'describe_security_group_references',682#  u'describe_security_groups',683#  u'describe_snapshot_attribute',684#  u'describe_snapshots',685#  u'describe_spot_datafeed_subscription',686#  u'describe_spot_fleet_instances',687#  u'describe_spot_fleet_request_history',688#  u'describe_spot_fleet_requests',689#  u'describe_spot_instance_requests',690#  u'describe_spot_price_history',691#  u'describe_stale_security_groups',692#  u'describe_tags',693#  u'describe_volume_attribute',694#  u'describe_volume_status',695#  u'describe_volumes',696#  u'describe_volumes_modifications',697#  u'describe_vpc_attribute',698#  u'describe_vpc_classic_link',699#  u'describe_vpc_classic_link_dns_support',700#  u'describe_vpc_endpoint_services',701#  u'describe_vpc_endpoints',702#  u'describe_vpcs',703#             704# =============================================================================705# --- main      706#  ------------------------------------------------------------------------ # 707#                                                                           # 708#                     main                                                  # 709#                                                                           # 710#  ------------------------------------------------------------------------ # 711def main():712    713    l_session = boto3.Session(profile_name = g_profile)714    l_region = l_session.region_name715    716    print('Configuration')717    print('-------------')718    print('    Current region: {}'.format(l_region))719    print('\n')720    721    ec2_resource = l_session.resource('ec2')   722    ec2_client   = l_session.client('ec2')     # lowest level723    724    remove_all_vpc(ec2_resource)725    726    # my_vpc_id = create_vpc(ec2_resource, ec2_client)727    # print('My VPC ID: {}, type = {}'.format(my_vpc_id.id, type(my_vpc_id.id)))728    729    730    # my_gateway_id = create_gateway(ec2_resource, my_vpc_id.id)731    # print('My Internet Gateway ID: {}'.format(my_gateway_id))732    733     734 #    for r in ec2_resource.meta.client.describe_vpcs()[ 'Vpcs']:735 #        l_vpc_id = r['VpcId']736 #        for s in r.meta.client.describe_internet_gateways()['InternetGateways']:737 #            print(s)    738#  ------------------------------------------------------------------------ # 739#                                                                           # 740#                     begin                                                 # 741#                                                                           # 742#  ------------------------------------------------------------------------ # 743            744if __name__ == "__main__":745    main()            ...migratelongerids.py
Source:migratelongerids.py  
...194        for resourcetype in ident_resources:195            counter = 1196            while counter <= MAXRETRY:197                try:198                    id_client_response = id_client.describe_identity_id_format(Resource=resourcetype,199                                                                            PrincipalArn=usersandroles)200                except ClientError as clierror:201                    log.info(("error code:", clierror.response['ResponseMetadata']['HTTPStatusCode'],202                              "\nrequest ID:", clierror.response['ResponseMetadata']['RequestId']))203                    log.info(("sleep for:", counter * DELAY * SECONDS))204                    sleep(counter * DELAY * SECONDS)205                    if counter <= MAXRETRY:206                        counter += 1207                    else:208                        log.info(clienterrormessage)209                        sys.exit(1)210                break211            for line in id_client_response['Statuses']:212                log.info(('%-100s: %-12s: %-20s' % (usersandroles, line['Resource'],...id_format.py
Source:id_format.py  
...10    def retrieve(self, conn):11        account_id = boto3.client('sts').get_caller_identity().get('Account')12        ARN = "arn:aws:iam::" + str(account_id) + ":root"13        print 'AWS account:',account_id, '   PrincipalArn:',ARN,'   AWS region:', conn.region_name,'\n'14        data = conn.describe_identity_id_format(PrincipalArn=ARN)15        for resource in data['Statuses']:16            item = {17                "Resource": resource['Resource'],18                'UseLongIds': resource['UseLongIds']19            }20            self.data[conn.region_name].append(item)21    def connect(self, region):22        conn = boto3.client('ec2', region_name=region)23        conn.region_name = region...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
