Advertisement
Guest User

Untitled

a guest
May 24th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # Authored by Chad Smith on 3/10/2015
  3. # please feel free to contact me at arpcefxl@gmail.com with comments or questions
  4. # assumes you have already run aws configure or are running in an ec2 role
  5.  
  6. import boto.ec2, sys
  7. region = sys.argv[1]
  8. secgroup = sys.argv[2]
  9. conn = boto.ec2.connect_to_region(region)
  10. allgroups = conn.get_all_security_groups()
  11. mygroup = conn.get_all_security_groups(groupnames=secgroup)
  12. groupname = mygroup[0].name
  13. groupid = mygroup[0].id
  14. group = mygroup[0]
  15.  
  16. for rule in group.rules:
  17. for grants in rule.grants:
  18. if grants.cidr_ip:
  19. print "revoking ingress rule with source as cidr_ip"
  20. print groupname, rule.ip_protocol, rule.from_port, rule.to_port, grants.cidr_ip
  21. conn.revoke_security_group(group_name=groupname, ip_protocol=rule.ip_protocol, from_port=rule.from_port, to_port=rule.to_port, cidr_ip=grants.cidr_ip)
  22. else:
  23. print "revoking ingress rule with source as security group"
  24. print groupname, rule.ip_protocol, rule.from_port, rule.to_port, grants.name
  25. if grants.name == 'amazon-elb-sg':
  26. print "revoking ingress rule with ELB as security group"
  27. conn.revoke_security_group(group_name=groupname, ip_protocol=rule.ip_protocol, from_port=rule.from_port, to_port=rule.to_port, src_security_group_group_id=grants.group_id,src_security_group_owner_id='amazon-elb')
  28. else:
  29. conn.revoke_security_group(group_name=groupname, ip_protocol=rule.ip_protocol, from_port=rule.from_port, to_port=rule.to_port, src_security_group_name=grants.name)
  30.  
  31. # handle cases where the security group is referred to by other security groups
  32. for othergroup in allgroups:
  33. for otherrule in othergroup.rules:
  34. for othergrant in otherrule.grants:
  35. grant_nom = othergrant.name or othergrant.group_id
  36. if grant_nom:
  37. if grant_nom == groupname:
  38. print "revoking ingress rule where source is the security group to be deleted"
  39. print othergroup.name, otherrule.ip_protocol, otherrule.from_port, otherrule.to_port, othergrant.name
  40. conn.revoke_security_group(group_name=othergroup.name, ip_protocol=otherrule.ip_protocol, from_port=otherrule.from_port, to_port=otherrule.to_port, src_security_group_name=groupname)
  41.  
  42. # delete the security group itself
  43. print "deleting security group"
  44. conn.delete_security_group(name=groupname)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement