Modifying rules for a given EC2 security group with Boto3

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

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.


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

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