简体   繁体   中英

Boto3 How to add a security group to an ec2 instance

ec2 = boto3.resource('ec2')

instance = ec2.create_instances(
 ImageId='ami-0fc970315c2d38f01',
 MinCount=1,
 MaxCount=1,
 InstanceType='t2.nano')
print(instance[0].id)

instance = ec2.create_security_group(GroupName='MyWebServer', Description = 'WebServer', VpcId='vpc-0dea879f34afff60d') 

This is what I have so far, it creates the instance and the security group for me but doesn't add both together. Any help would be appreciated

This just overwrites the instance variable with the security group:

instance = ec2.create_security_group(GroupName='MyWebServer', Description = 'WebServer', VpcId='vpc-0dea879f34afff60d') 

There's nothing in your code that is making any attempt to assign the security group to the EC2 instances. The easiest way is to create the security group first, and then include it in the create_instances call, like this:

sg = ec2.create_security_group(GroupName='MyWebServer', Description = 'WebServer', VpcId='vpc-0dea879f34afff60d')

instance = ec2.create_instances(
 ImageId='ami-0fc970315c2d38f01',
 MinCount=1,
 MaxCount=1,
 InstanceType='t2.nano',
 SecurityGroups=[ sg.group_id ] 
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM