使用boto3如何将VPC与EC2实例关联?

6

我正在尝试使用boto3创建EC2实例:

#!/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': 'person@email.com'} ])

问题:VpcId='vpc-22222222'是正确的方式来指定用于创建这个EC2实例的VPC吗?我无法找到一个好的示例,而且boto3文档有点晦涩,还描述了创建VPC与使用现有VPC的区别。

1个回答

6

您正在将EC2实例启动到VPC的子网中,因此您必须提供子网ID。如果需要,AWS可以推断出VPC。

在boto3中,在调用create_instances时提供NetworkInterfaces参数,例如:

NetworkInterfaces = [
    {
        'SubnetId': subnet_id,
        'DeviceIndex': 0,
        'AssociatePublicIpAddress': True,
        'Groups': [sg1, sg2]
    }
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接