Friday, February 4, 2022

[SOLVED] Boto3 How to add a security group to an ec2 instance

Issue

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


Solution

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



Answered By - Mark B
Answer Checked By - Mary Flores (WPSolving Volunteer)