kamal
kamal

Reputation: 9785

using boto3 how can i associate a vpc with ec2 instance

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.

Upvotes: 6

Views: 3875

Answers (1)

jarmod
jarmod

Reputation: 78890

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]
    }
]

Upvotes: 6

Related Questions