Skip to content

Instantly share code, notes, and snippets.

@viesti
Created October 11, 2015 19:28
Show Gist options
  • Save viesti/786f5d93621985556b78 to your computer and use it in GitHub Desktop.
Save viesti/786f5d93621985556b78 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
def main():
module = AnsibleModule(
argument_spec = dict(
ec2_id = dict(required=True),
group_names = dict(required=True),
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")
group_ids = set([group.id for group in connection.get_all_security_groups(group_names)])
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()
@weirdbricks
Copy link

hi @viesti, I was wondering if there's an easy way to specify a VPC for this script? When I try running it, it's trying to use the default VPC on the account. Many thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment