Best Python code snippet using localstack_python
vpc.py
Source:vpc.py
1import json2import logging3import datetime as dt4import time5import boto36from botocore import ClientError78myclient = boto3.client('ec2')910def createpolicy(policy_name):11 try:12 my_managed_policy = {13 "Version": "2012-10-17",14 "Statement": [15 {16 "Effect": "Allow",17 "Action": [18 "ec2:AcceptVpcPeeringConnection",19 "ec2:AcceptVpcEndpointConnections",20 "ec2:AllocateAddress",21 "ec2:AssignIpv6Addresses",22 "ec2:AssignPrivateIpAddresses",23 "ec2:AssociateAddress",24 "ec2:AssociateDhcpOptions",25 "ec2:AssociateRouteTable",26 "ec2:AssociateSubnetCidrBlock",27 "ec2:AssociateVpcCidrBlock",28 "ec2:AttachClassicLinkVpc",29 "ec2:AttachInternetGateway",30 "ec2:AttachNetworkInterface",31 "ec2:AttachVpnGateway",32 "ec2:AuthorizeSecurityGroupEgress",33 "ec2:AuthorizeSecurityGroupIngress",34 "ec2:CreateCarrierGateway",35 "ec2:CreateCustomerGateway",36 "ec2:CreateDefaultSubnet",37 "ec2:CreateDefaultVpc",38 "ec2:CreateDhcpOptions",39 "ec2:CreateEgressOnlyInternetGateway",40 "ec2:CreateFlowLogs",41 "ec2:CreateInternetGateway",42 "ec2:CreateLocalGatewayRouteTableVpcAssociation",43 "ec2:CreateNatGateway",44 "ec2:CreateNetworkAcl",45 "ec2:CreateNetworkAclEntry",46 "ec2:CreateNetworkInterface",47 "ec2:CreateNetworkInterfacePermission",48 "ec2:CreateRoute",49 "ec2:CreateRouteTable",50 "ec2:CreateSecurityGroup",51 "ec2:CreateSubnet",52 "ec2:CreateTags",53 "ec2:CreateVpc",54 "ec2:CreateVpcEndpoint",55 "ec2:CreateVpcEndpointConnectionNotification",56 "ec2:CreateVpcEndpointServiceConfiguration",57 "ec2:CreateVpcPeeringConnection",58 "ec2:CreateVpnConnection",59 "ec2:CreateVpnConnectionRoute",60 "ec2:CreateVpnGateway",61 "ec2:DeleteCarrierGateway",62 "ec2:DeleteCustomerGateway",63 "ec2:DeleteDhcpOptions",64 "ec2:DeleteEgressOnlyInternetGateway",65 "ec2:DeleteFlowLogs",66 "ec2:DeleteInternetGateway",67 "ec2:DeleteLocalGatewayRouteTableVpcAssociation",68 "ec2:DeleteNatGateway",69 "ec2:DeleteNetworkAcl",70 "ec2:DeleteNetworkAclEntry",71 "ec2:DeleteNetworkInterface",72 "ec2:DeleteNetworkInterfacePermission",73 "ec2:DeleteRoute",74 "ec2:DeleteRouteTable",75 "ec2:DeleteSecurityGroup",76 "ec2:DeleteSubnet",77 "ec2:DeleteTags",78 "ec2:DeleteVpc",79 "ec2:DeleteVpcEndpoints",80 "ec2:DeleteVpcEndpointConnectionNotifications",81 "ec2:DeleteVpcEndpointServiceConfigurations",82 "ec2:DeleteVpcPeeringConnection",83 "ec2:DeleteVpnConnection",84 "ec2:DeleteVpnConnectionRoute",85 "ec2:DeleteVpnGateway",86 "ec2:DescribeAccountAttributes",87 "ec2:DescribeAddresses",88 "ec2:DescribeAvailabilityZones",89 "ec2:DescribeCarrierGateways",90 "ec2:DescribeClassicLinkInstances",91 "ec2:DescribeCustomerGateways",92 "ec2:DescribeDhcpOptions",93 "ec2:DescribeEgressOnlyInternetGateways",94 "ec2:DescribeFlowLogs",95 "ec2:DescribeInstances",96 "ec2:DescribeInternetGateways",97 "ec2:DescribeIpv6Pools",98 "ec2:DescribeLocalGatewayRouteTables",99 "ec2:DescribeLocalGatewayRouteTableVpcAssociations",100 "ec2:DescribeKeyPairs",101 "ec2:DescribeMovingAddresses",102 "ec2:DescribeNatGateways",103 "ec2:DescribeNetworkAcls",104 "ec2:DescribeNetworkInterfaceAttribute",105 "ec2:DescribeNetworkInterfacePermissions",106 "ec2:DescribeNetworkInterfaces",107 "ec2:DescribePrefixLists",108 "ec2:DescribeRouteTables",109 "ec2:DescribeSecurityGroupReferences",110 "ec2:DescribeSecurityGroupRules",111 "ec2:DescribeSecurityGroups",112 "ec2:DescribeStaleSecurityGroups",113 "ec2:DescribeSubnets",114 "ec2:DescribeTags",115 "ec2:DescribeVpcAttribute",116 "ec2:DescribeVpcClassicLink",117 "ec2:DescribeVpcClassicLinkDnsSupport",118 "ec2:DescribeVpcEndpointConnectionNotifications",119 "ec2:DescribeVpcEndpointConnections",120 "ec2:DescribeVpcEndpoints",121 "ec2:DescribeVpcEndpointServiceConfigurations",122 "ec2:DescribeVpcEndpointServicePermissions",123 "ec2:DescribeVpcEndpointServices",124 "ec2:DescribeVpcPeeringConnections",125 "ec2:DescribeVpcs",126 "ec2:DescribeVpnConnections",127 "ec2:DescribeVpnGateways",128 "ec2:DetachClassicLinkVpc",129 "ec2:DetachInternetGateway",130 "ec2:DetachNetworkInterface",131 "ec2:DetachVpnGateway",132 "ec2:DisableVgwRoutePropagation",133 "ec2:DisableVpcClassicLink",134 "ec2:DisableVpcClassicLinkDnsSupport",135 "ec2:DisassociateAddress",136 "ec2:DisassociateRouteTable",137 "ec2:DisassociateSubnetCidrBlock",138 "ec2:DisassociateVpcCidrBlock",139 "ec2:EnableVgwRoutePropagation",140 "ec2:EnableVpcClassicLink",141 "ec2:EnableVpcClassicLinkDnsSupport",142 "ec2:ModifyNetworkInterfaceAttribute",143 "ec2:ModifySecurityGroupRules",144 "ec2:ModifySubnetAttribute",145 "ec2:ModifyVpcAttribute",146 "ec2:ModifyVpcEndpoint",147 "ec2:ModifyVpcEndpointConnectionNotification",148 "ec2:ModifyVpcEndpointServiceConfiguration",149 "ec2:ModifyVpcEndpointServicePermissions",150 "ec2:ModifyVpcPeeringConnectionOptions",151 "ec2:ModifyVpcTenancy",152 "ec2:MoveAddressToVpc",153 "ec2:RejectVpcEndpointConnections",154 "ec2:RejectVpcPeeringConnection",155 "ec2:ReleaseAddress",156 "ec2:ReplaceNetworkAclAssociation",157 "ec2:ReplaceNetworkAclEntry",158 "ec2:ReplaceRoute",159 "ec2:ReplaceRouteTableAssociation",160 "ec2:ResetNetworkInterfaceAttribute",161 "ec2:RestoreAddressToClassic",162 "ec2:RevokeSecurityGroupEgress",163 "ec2:RevokeSecurityGroupIngress",164 "ec2:UnassignIpv6Addresses",165 "ec2:UnassignPrivateIpAddresses",166 "ec2:UpdateSecurityGroupRuleDescriptionsEgress",167 "ec2:UpdateSecurityGroupRuleDescriptionsIngress"168 ],169 "Resource": "*"170 }171 ]172 }173174 response = myclient.create_policy(PolicyName=policy_name, PolicyDocument=json.dumps(my_managed_policy))175 print(response)176 logging.info("Policy created", 'AmazonVPCFullAccess')177 except ClientError:178 logging.exception("Policy creation %s failed", 'AmazonVPCFullAccess')179 raise180181182def attachUserPolicy():183 try:184 response = client.attach_user_policy(185 UserName='myvpc', # Name of user186 PolicyArn='arn:aws:iam::aws:policy/AmazonVPCFullAccess'187 # Policy ARN which you want to assign to user188 )189 print(response)190 logging.info("Attach policy %s from user %s.", 'myvpc', 'arn:aws:iam::aws:policy/AmazonVPCFullAccess')191 except ClientError:192 logging.exception("Attaching policy %s to user %s failed", 'myvpc',193 'arn:aws:iam::aws:policy/AmazonVPCFullAccess')194 raise195196197#myami = 'ami-0629230e074c580f2'198199vpc=myclient.create_vpc(CidrBlock='10.0.0.0/16')200201tag = vpc.create_tags(Tags=[{'Key': 'Name', 'Value': 'demo-vpc'}])202vpc.wait_until_available()203time.sleep(10)204sub1=myclient.crete_subnet(CidrBlock='10.0.20.0/24',VpcId=vpc.id)205tag1 = sub1.create_tags(Tags=[{206 'Key':'Name',207 'Value':'public'208}])209210ig = myclient.create_internet_gateway()211vpc.attach_internet_gateway(InternetGatewayId=ig.id)212print(ig.id)213214route_table = vpc.create_route_table()215route = route_table.create_route(216 DestinationCidrBlock='0.0.0.0/0',217 GatewayId=ig.id218)219print(route_table.id)220221myclient.create_subnet(CidrBlock='192.168.10.0/28',VpcId=vpc.id)222223224response = route_table.associate_with_subnet(SubnetId=sub1)225print(response)226227G_name = input("Enter group_name:")228print(G_name)229230sec_group = myclient.create_security_group(231 GroupName=G_name, Description='slice_0 sec group', VpcId=vpc.id)232sec_group.authorize_ingress(233 CidrIp='0.0.0.0/0',234 IpProtocol='icmp',235 FromPort=-1,236 ToPort=-1237)238print(sec_group.id)239240Image_id = input("Enter ami:")241print(Image_id)242243instances = myclient.create_instances(244 ImageId=Image_id, InstanceType='t2.micro', MaxCount=1, MinCount=1,245 NetworkInterfaces=[246 {'SubnetId': sub1, 'DeviceIndex': 0, 'AssociatePublicIpAddress': True, 'Groups': [sec_group.group_id]}])247instances[0].wait_until_running()248print(instances[0].id)249250
...
ec2_2_list_instances.py
Source:ec2_2_list_instances.py
1import boto32from CloudFormation.region import region3ec2 = boto3.resource('ec2', region_name=region)4ec2_client = boto3.client('ec2', region_name=region)5def ec2_list_all():6 """7 ååºææå®ä¾8 :return å®ä¾æ¸
å:9 """10 # instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])11 instances = ec2.instances.filter()12 instances_list = []13 for instance in instances:14 instances_list.append(instance.id)15 return instances_list16 # response = ec2client.describe_instances()17 # return response['Reservations'][0]['Instances']18def ec2_list_no_terminate():19 """20 ååºæææªè¢«ç»ç»çå®ä¾21 :return å®ä¾æ¸
å:22 """23 # instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])24 instances = ec2.instances.filter()25 instances_list = []26 for instance in instances:27 if instance.state.get('Name') != 'terminated':28 instances_list.append(instance.id)29 return instances_list30def ec2_list_by_state(ec2_state):31 """32 è¿åç¹å®ç¶æçå®ä¾33 :param ec2_state (å®ä¾ç¶æ):34 :return å®ä¾æ¸
å:35 """36 instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': [ec2_state]}])37 # instances = ec2.instances.filter()38 instances_list = []39 for instance in instances:40 if instance.state.get('Name') != 'terminated':41 instances_list.append(instance.id)42 return instances_list43def ec2_get_by_tagname(instance_name):44 """45 æ¾å°æ ç¾Name, å¼ä¸ºè¾å
¥åæ°çå®ä¾46 :param instance_name:47 :return å®ä¾æ¸
å:48 """49 instances = ec2.instances.filter()50 instances_list = []51 for instance in instances:52 if {'Key': 'Name', 'Value': instance_name} in instance.tags and instance.state.get('Name') != 'terminated':53 instances_list.append(instance.id)54 return instances_list55def ec2_instance_detail(instance_id):56 """57 æ¥è¯¢ç¹å®å®ä¾ç详ç»ä¿¡æ¯58 :param instance_id (å®ä¾ID):59 :return ç¹æ§å®ä¾ç详ç»ä¿¡æ¯:60 """61 # åªè½å¨å表ä¸ä¼ å
¥ä¸ä¸ªID62 specificinstance = ec2_client.describe_instances(InstanceIds=[instance_id])63 return specificinstance.get('Reservations')[0].get('Instances')[0]64if __name__ == '__main__':65 from pprint import pprint66 # print(ec2_list_all())67 # print(ec2_list_no_terminate())68 # pprint(ec2_instance_detail(ec2_list_no_terminate()[0]))69 # print(ec2_instance_detail(ec2_list_no_terminate()[0]).get('SecurityGroups'))70 # print(ec2_instance_detail(ec2_list_no_terminate()[0]).get('PublicIpAddress'))71 # for instance in ec2_list_by_state('running'):72 # print(ec2_instance_detail(instance).get('PublicIpAddress'))...
ec2_description.py
Source:ec2_description.py
1from __future__ import absolute_import2import os3import boto34import datetime5import splunksdc.log as logging6import splunk_ta_aws.common.ta_aws_consts as tac7from . import description as desc8logger = logging.get_module_logger()9CREDENTIAL_THRESHOLD=datetime.timedelta(minutes=20)10def get_ec2_conn(config):11 return desc.BotoRetryWrapper(boto_client=boto3.client(12 'ec2',13 region_name=config.get(tac.region),14 aws_access_key_id=config.get(tac.key_id),15 aws_secret_access_key=config.get(tac.secret_key),16 aws_session_token=config.get('aws_session_token')17 ))18@desc.generate_credentials19@desc.decorate20def ec2_instances(config):21 ec2_conn = get_ec2_conn(config)22 paginator = ec2_conn.get_paginator('describe_instances')23 for page in paginator.paginate():24 for reservation in page.get('Reservations', []):25 for instance in reservation.get('Instances', []):26 instance['OwnerId'] = reservation.get('OwnerId')27 yield instance28 desc.refresh_credentials(config,CREDENTIAL_THRESHOLD,ec2_conn)29@desc.generate_credentials30@desc.decorate31def ec2_reserved_instances(config):32 ec2_conn = get_ec2_conn(config)33 res = ec2_conn.describe_reserved_instances()34 for reserved_instance in res.get('ReservedInstances', []):35 yield reserved_instance36@desc.generate_credentials37@desc.decorate38def ec2_ebs_snapshots(config):39 ec2_conn = get_ec2_conn(config)40 paginator = ec2_conn.get_paginator('describe_snapshots')41 for page in paginator.paginate():42 for item in page.get('Snapshots', []):43 yield item44 desc.refresh_credentials(config,CREDENTIAL_THRESHOLD,ec2_conn)45@desc.generate_credentials46@desc.decorate47def ec2_volumes(config):48 ec2_conn = get_ec2_conn(config)49 paginator = ec2_conn.get_paginator('describe_volumes')50 for page in paginator.paginate():51 for volume in page.get('Volumes', []):52 yield volume53 desc.refresh_credentials(config,CREDENTIAL_THRESHOLD,ec2_conn)54@desc.generate_credentials55@desc.decorate56def ec2_security_groups(config):57 ec2_conn = get_ec2_conn(config)58 paginator = ec2_conn.get_paginator('describe_security_groups')59 for page in paginator.paginate():60 for security_group in page.get('SecurityGroups', []):61 yield security_group62 desc.refresh_credentials(config,CREDENTIAL_THRESHOLD,ec2_conn)63@desc.generate_credentials64@desc.decorate65def ec2_key_pairs(config):66 ec2_conn = get_ec2_conn(config)67 res = ec2_conn.describe_key_pairs()68 for key_pair in res.get('KeyPairs', []):69 yield key_pair70@desc.generate_credentials71@desc.decorate72def ec2_images(config):73 ec2_conn = get_ec2_conn(config)74 res = ec2_conn.describe_images(Owners=['self'])75 76 for image in res.get('Images', []):77 yield image78@desc.generate_credentials79@desc.decorate80def ec2_addresses(config):81 ec2_conn = get_ec2_conn(config) 82 res = ec2_conn.describe_addresses()83 for address in res.get('Addresses', []):...
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!!