Home > Blockchain >  Boto3 add security group to EC2 instance
Boto3 add security group to EC2 instance

Time:07-03

I create instances like so:

client = boto3.client('ec2', region_name="eu-central-1")
client.run_instances(ImageId="ami-0df63501d4a3233e8", MinCount=1, MaxCount=1)

But how can I specify the type, securitygroup, etc. ?

Are they already stored in the ami ?

I have seen a solution using boto3.resources("ec2") which I have already tried, but then I can't properly run UnitTests on it.

CodePudding user response:

You would add the parameter SecurityGroupIds if you want to add one or more by the ID or SecurityGroups if you want to add by the name of the security group. Both of these should be of type list.

client = boto3.client('ec2', region_name='eu-central-1')
client.run_instances(ImageId='ami-0df63501d4a3233e8', MinCount=1, MaxCount=1,
                     SecurityGroupIds=['sg-000000000000000'])

Replace sg-000000000000000 with your real security group ID.

  • Related