I am trying to create an ec2 instance using boto3:
#!/usr/bin/env python
import boto3
import json
from collections import defaultdict
ec2 = boto3.resource('ec2', region_name='us-west-1')
print ("Creating instance...")
ec2info = defaultdict()
vpc = ec2.Vpc('vpc-22222222')
instance = ec2.create_instances(
VpcId='vpc-22222222'
ImageId='ami-aaaaaaa',
SubnetId='subnet-99999999',
KeyName='skahmed-gss',
SecurityGroupIds=["sg-5555555","sg-9999999"],
MinCount=1,
MaxCount=1,
InstanceType='t2.micro',
#BlockDeviceMappings=[{"DeviceName": "/dev/xvda","Ebs" : { "VolumeSize" : 350 }}]
BlockDeviceMappings=[
{
'DeviceName': '/dev/sda1',
'Ebs': {
'VolumeSize': 20,
'VolumeType': 'gp2'
}
}
]
)
print("Instance ID: " + instance[0].id)
ec2.create_tags(Resources = [instance[0].id], Tags = [{'Key': 'Name', 'Value': 'SWALK-CENTOS7'}, {'Key': 'Environment', 'Value': 'NON_PROD'},
{'Key': 'scheduler:ec2-startstop', 'Value': 'default'}, {'Key': 'Server_Function', 'Value': 'Spacewalk'}, {'Key': 'System', 'Value': 'GSS/C
hef'}, {'Key': 'Fisma_Id', 'Value': 'CIS-0000-MMM-1111'}, {'Key': 'POC', 'Value': '[email protected]'} ])
Question: is VpcId='vpc-22222222' the correct way to specify the vpc being used for this ec2 instance creation ? i could not find a decent example and boto3 doc is a bit cryptic, plus it describes creating a VPC as compared to using an existing one.
Amazon Virtual Private Cloud (Amazon VPC) enables you to define a virtual network in your own logically isolated area within the AWS cloud, known as a virtual private cloud or VPC. You can create AWS resources, such as Amazon EC2 instances, into the subnets of your VPC.
An internet gateway must be attached to the VPC. The route tables associated with your public subnet (including custom route tables) must have a route to the internet gateway. The security groups and network access control lists (ACL) associated with your VPC must allow traffic to flow to and from the internet.
You are launching the EC2 instance into a subnet of a VPC and so you have to supply the subnet ID. AWS can then infer the VPC, if needed.
In boto3, supply the NetworkInterfaces parameter when calling create_instances, for example:
NetworkInterfaces = [
{
'SubnetId': subnet_id,
'DeviceIndex': 0,
'AssociatePublicIpAddress': True,
'Groups': [sg1, sg2]
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With