Modifying rules for a given EC2 security group with Boto3

Question:

I have recently been working on programatically adding and removing ingress rules to security groups on my EC2 server. However, I now seem to have hit a bit of a wall.

I would like to be able to modify existing rules through a python script, but I haven’t been able to find any guidance on the Boto3 docs.

Is there any way in which this can be done?

Thanks

Asked By: User588233

||

Answers:

See Boto3:SecurityGroup

There is no API to modify a rule in SG. You have to revoke the rule first and then add the rule with the modified parameters using authorize. The link also has code snippets.

  • authorize_egress()
  • authorize_ingress()
  • revoke_egress()
  • revoke_ingress()
Answered By: helloV

Seems like there are no way to modify security group rule. You have to delete the old one:

security_group.revoke_ingress(IpProtocol="tcp", CidrIp="0.0.0.0/0", FromPort=3306, ToPort=3306)

and add the new one:

security_group.authorize_ingress(IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=3306,ToPort=3306)

Hope it help.

Answered By: DonerKebab

AWS has added new API(modify_security_group_rules) wherein security group rule can be modified. Below code for reference:

import boto3
client = boto3.client('ec2')
sg_rules_list = [{'SecurityGroupRuleId': 'sgr-07de36a0521f39c8b',
                  'SecurityGroupRule': {
                      'IpProtocol': 'tcp',
                      'FromPort': 22,
                      'ToPort': 22,
                      'CidrIpv4': '3.3.3.3/32',
                      'Description': 'added ssh port'
                  }
                  }
                 ]
response = client.modify_security_group_rules(GroupId='sg-00f3b9232325b20fb',
                                              SecurityGroupRules=sg_rules_list)

More details on this on AWS blog: Easily Manage Security Group Rules with the New Security Group Rule ID

Answered By: Randhir Kumar