Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 784
kamal Avatar asked Feb 08 '18 17:02

kamal


People also ask

Are EC2 instances in VPC?

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.

What should be attached to a VPC for users to connect to EC2 instance from the Internet?

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.


1 Answers

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]
    }
]
like image 181
jarmod Avatar answered Sep 21 '22 05:09

jarmod