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
When you associate multiple security groups with an instance, the rules from each security group are effectively aggregated to create one set of rules. Amazon EC2 uses this set of rules to determine whether to allow access. You can assign multiple security groups to an instance. Therefore, an instance can have hundreds of rules that apply.
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.
An Amazon EC2 security group acts as a virtual firewall that controls the traffic for one or more instances. You add rules to each security group to allow traffic to or from its associated instances.
Before creating an EC2 instance using Boto3, you have to set up an SSH key in your account. You must have an SSH key during the EC2 instance launch if you’re not using AWS Systems Manager and are willing to have remote access to your EC2 instance. In addition to that, you’ll need an SSH key to get the Windows EC2 instance password.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With