import boto3 sess=boto3.session.Session() res=sess.resource('ec2') #-------------------Create-VPC--------------------------- vpc=res.create_vpc(CidrBlock='192.168.0.1/16') vpc.create_tags(Tags=[ { 'Key': 'Name', 'Value': 'Boto_test_VPC' }, ]) vpc.wait_until_available() x=vpc.id print(x) #-------------------InternetGatewayId----------------------- ig=res.create_internet_gateway() vpc.attach_internet_gateway(InternetGatewayId=ig.id) y=ig.id print(y) #---------------------RouteTable------------------------------ route_table=vpc.create_route_table() route_table.create_route(DestinationCidrBlock="0.0.0.0/0", GatewayId=ig.id) z=route_table.id print(z) #--------------------Create-Subnets--------------------------- subnet=res.create_subnet(CidrBlock="192.168.1.1/24",VpcId=vpc.id) a=subnet.id print(a) route_table.associate_with_subnet(SubnetId=subnet.id) #------------------Create-SecurityGroup--------------------------- sec_group=res.create_security_group(GroupName="Boto_test", Description="For_Boto_Testing",VpcId=vpc.id) sec_group.authorize_ingress(CidrIp='0.0.0.0/0',IpProtocol='icmp',FromPort=-1,ToPort=-1) sg=sec_group.id print(sg) #--------------------Create-Ec2-Instance--------------------------- ec2 = boto3.resource('ec2') # create a file to store the key locally outfile = open('Boto3-test12.pem','w') # call the boto ec2 function to create a key pair key_pair = ec2.create_key_pair(KeyName='Boto3-test12') # capture the key and store it in a file KeyPairOut = str(key_pair.key_material) outfile.write(KeyPairOut) print("Key Pair Boto3-test12.pem successfully created") inst=res.create_instances(ImageId='ami-0885b1f6bd170450c',InstanceType='t2.micro', KeyName='Boto3-test12',MaxCount=1,MinCount=1, NetworkInterfaces=[{'SubnetId':subnet.id,'DeviceIndex':0, 'AssociatePublicIpAddress': True, 'Groups':[sec_group.group_id]}]) inst[0].wait_until_running() print(inst[0]) print("EC2 instance successfully created with using VPC, Subnets, InternetGateway, SecurityGroup ") #----------------------Complete-----------------------------