Skip to content

Instantly share code, notes, and snippets.

@weirdbricks
Forked from viesti/ec2_group_set
Created October 14, 2017 00:08
Show Gist options
  • Save weirdbricks/3d90486cc3e0b69c658ac6ea29a48f07 to your computer and use it in GitHub Desktop.
Save weirdbricks/3d90486cc3e0b69c658ac6ea29a48f07 to your computer and use it in GitHub Desktop.
Alter security groups on EC2 nodes
#!/usr/bin/python
from boto.ec2 import connect_to_region
from boto.ec2.group import Group
from pprint import pprint
def main():
module = AnsibleModule(
argument_spec = dict(
ec2_id = dict(required=True),
group_names = dict(required=True),
vpc_id = dict(required=False),
region = dict(required=True)))
connection = connect_to_region(module.params.get("region"))
ec2_id = module.params.get("ec2_id")
group_names = module.params.get("group_names")
vpc_id = module.params.get("vpc_id")
if vpc_id:
filters = {'vpc-id': vpc_id, 'group-name': group_names}
else:
filters = {'group-name': group_names}
# examples stolen from: http://nullege.com/codes/search/boto.ec2.connection.EC2Connection.get_all_security_groups?fulldoc=1
group_ids = set([group.id for group in connection.get_all_security_groups(filters=filters)])
current_group_ids = set([group.id for group in connection.get_instance_attribute(ec2_id, "groupSet")["groupSet"]])
if connection.modify_instance_attribute(ec2_id, "groupSet", current_group_ids.union(group_ids)):
current_groups = connection.get_instance_attribute(ec2_id, "groupSet")["groupSet"]
module.exit_json(changed=True, groups=[group.id for group in current_groups])
else:
module.fail_json(msg="Could not update groups")
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment