Huw
Huw

Reputation: 523

Python Boto AWS Remove VPC Security Group Rules

I'm currently automating the build of an AWS VPC but wish to remove the default rules added to the security group created with the VPC. I can view security group rules like so:

for security_group in vpc_connection.get_all_security_groups(): for rule in vpc_security_group.rules: print dir(rule)

I'd be grateful if anyone could tell me or give me an example of how to remove the default rules from the VPC.

From the API documentation I can see that there are a few methods such as:

boto.ec2.connection.revoke_security_group()

However I am not clear on what needs to be passed in as arguments if this is indeed the correct method.

Many thanks

H

Upvotes: 5

Views: 2549

Answers (2)

Chad Smith
Chad Smith

Reputation: 146

I used some of your logic above to craft a couple python scripts that will remove a security group whether it is in ec2-classic or VPC (assuming ingress rules only). There are a couple special cases, such as your SG to be deleted is referenced in an ingress rule in another SG. Another special case is referencing the AWS default SG for ELB in EC2-classic. Both are handled gracefully, and the scripts can be found here: https://gist.github.com/arpcefxl/2acd7d873b95dbebcd42

Upvotes: 0

Huw
Huw

Reputation: 523

I figured this out in the end:

for rule in vpc_security_group.rules:
    for grant in rule.grants:
        ec2_connection.revoke_security_group(group_id=vpc_security_group.id, ip_protocol=rule.ip_protocol, from_port=rule.from_port, to_port=rule.to_port, src_security_group_group_id=grant.group_id, cidr_ip=grant.cidr_ip)

for rule in vpc_security_group.rules_egress:
    for grant in rule.grants:
        ec2_connection.revoke_security_group_egress(vpc_security_group.id, rule.ip_protocol, rule.from_port, rule.to_port, grant.group_id, grant.cidr_ip)

Upvotes: 6

Related Questions