Don't raise or catch StandardError in amazon modules

reviewable/pr18780/r1
Toshio Kuratomi 9 years ago
parent 60dd37d15f
commit 3c4f954f0f

@ -268,8 +268,7 @@ def main():
try: try:
connection = connect_to_aws(boto.dynamodb2, region, **aws_connect_params) connection = connect_to_aws(boto.dynamodb2, region, **aws_connect_params)
except (NoAuthHandlerFound, AnsibleAWSError), e:
except (NoAuthHandlerFound, StandardError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
state = module.params.get('state') state = module.params.get('state')

@ -184,7 +184,7 @@ def main():
if region: if region:
try: try:
connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params) connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")
@ -194,4 +194,5 @@ def main():
from ansible.module_utils.basic import * from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import * from ansible.module_utils.ec2 import *
main() if __name__ == '__main__':
main()

@ -96,25 +96,25 @@ EXAMPLES = '''
private_ip_address: 172.31.0.20 private_ip_address: 172.31.0.20
subnet_id: subnet-xxxxxxxx subnet_id: subnet-xxxxxxxx
state: present state: present
# Destroy an ENI, detaching it from any instance if necessary # Destroy an ENI, detaching it from any instance if necessary
- ec2_eni: - ec2_eni:
eni_id: eni-xxxxxxx eni_id: eni-xxxxxxx
force_detach: yes force_detach: yes
state: absent state: absent
# Update an ENI # Update an ENI
- ec2_eni: - ec2_eni:
eni_id: eni-xxxxxxx eni_id: eni-xxxxxxx
description: "My new description" description: "My new description"
state: present state: present
# Detach an ENI from an instance # Detach an ENI from an instance
- ec2_eni: - ec2_eni:
eni_id: eni-xxxxxxx eni_id: eni-xxxxxxx
instance_id: None instance_id: None
state: present state: present
### Delete an interface on termination ### Delete an interface on termination
# First create the interface # First create the interface
- ec2_eni: - ec2_eni:
@ -124,7 +124,7 @@ EXAMPLES = '''
subnet_id: subnet-xxxxxxxx subnet_id: subnet-xxxxxxxx
state: present state: present
register: eni register: eni
# Modify the interface to enable the delete_on_terminaton flag # Modify the interface to enable the delete_on_terminaton flag
- ec2_eni: - ec2_eni:
eni_id: {{ "eni.interface.id" }} eni_id: {{ "eni.interface.id" }}
@ -145,14 +145,14 @@ except ImportError:
def get_error_message(xml_string): def get_error_message(xml_string):
root = ET.fromstring(xml_string) root = ET.fromstring(xml_string)
for message in root.findall('.//Message'): for message in root.findall('.//Message'):
return message.text return message.text
def get_eni_info(interface): def get_eni_info(interface):
interface_info = {'id': interface.id, interface_info = {'id': interface.id,
'subnet_id': interface.subnet_id, 'subnet_id': interface.subnet_id,
'vpc_id': interface.vpc_id, 'vpc_id': interface.vpc_id,
@ -164,7 +164,7 @@ def get_eni_info(interface):
'source_dest_check': interface.source_dest_check, 'source_dest_check': interface.source_dest_check,
'groups': dict((group.id, group.name) for group in interface.groups), 'groups': dict((group.id, group.name) for group in interface.groups),
} }
if interface.attachment is not None: if interface.attachment is not None:
interface_info['attachment'] = {'attachment_id': interface.attachment.id, interface_info['attachment'] = {'attachment_id': interface.attachment.id,
'instance_id': interface.attachment.instance_id, 'instance_id': interface.attachment.instance_id,
@ -173,11 +173,11 @@ def get_eni_info(interface):
'attach_time': interface.attachment.attach_time, 'attach_time': interface.attachment.attach_time,
'delete_on_termination': interface.attachment.delete_on_termination, 'delete_on_termination': interface.attachment.delete_on_termination,
} }
return interface_info return interface_info
def wait_for_eni(eni, status): def wait_for_eni(eni, status):
while True: while True:
time.sleep(3) time.sleep(3)
eni.update() eni.update()
@ -188,23 +188,20 @@ def wait_for_eni(eni, status):
else: else:
if status == "attached" and eni.attachment.status == "attached": if status == "attached" and eni.attachment.status == "attached":
break break
def create_eni(connection, module): def create_eni(connection, module):
instance_id = module.params.get("instance_id") instance_id = module.params.get("instance_id")
if instance_id == 'None': if instance_id == 'None':
instance_id = None instance_id = None
do_detach = True
else:
do_detach = False
device_index = module.params.get("device_index") device_index = module.params.get("device_index")
subnet_id = module.params.get('subnet_id') subnet_id = module.params.get('subnet_id')
private_ip_address = module.params.get('private_ip_address') private_ip_address = module.params.get('private_ip_address')
description = module.params.get('description') description = module.params.get('description')
security_groups = module.params.get('security_groups') security_groups = module.params.get('security_groups')
changed = False changed = False
try: try:
eni = compare_eni(connection, module) eni = compare_eni(connection, module)
if eni is None: if eni is None:
@ -212,22 +209,22 @@ def create_eni(connection, module):
if instance_id is not None: if instance_id is not None:
try: try:
eni.attach(instance_id, device_index) eni.attach(instance_id, device_index)
except BotoServerError as ex: except BotoServerError:
eni.delete() eni.delete()
raise raise
# Wait to allow creation / attachment to finish # Wait to allow creation / attachment to finish
wait_for_eni(eni, "attached") wait_for_eni(eni, "attached")
eni.update() eni.update()
changed = True changed = True
except BotoServerError as e: except BotoServerError as e:
module.fail_json(msg=get_error_message(e.args[2])) module.fail_json(msg=get_error_message(e.args[2]))
module.exit_json(changed=changed, interface=get_eni_info(eni)) module.exit_json(changed=changed, interface=get_eni_info(eni))
def modify_eni(connection, module): def modify_eni(connection, module):
eni_id = module.params.get("eni_id") eni_id = module.params.get("eni_id")
instance_id = module.params.get("instance_id") instance_id = module.params.get("instance_id")
if instance_id == 'None': if instance_id == 'None':
@ -236,8 +233,6 @@ def modify_eni(connection, module):
else: else:
do_detach = False do_detach = False
device_index = module.params.get("device_index") device_index = module.params.get("device_index")
subnet_id = module.params.get('subnet_id')
private_ip_address = module.params.get('private_ip_address')
description = module.params.get('description') description = module.params.get('description')
security_groups = module.params.get('security_groups') security_groups = module.params.get('security_groups')
force_detach = module.params.get("force_detach") force_detach = module.params.get("force_detach")
@ -245,7 +240,6 @@ def modify_eni(connection, module):
delete_on_termination = module.params.get("delete_on_termination") delete_on_termination = module.params.get("delete_on_termination")
changed = False changed = False
try: try:
# Get the eni with the eni_id specified # Get the eni with the eni_id specified
eni_result_set = connection.get_all_network_interfaces(eni_id) eni_result_set = connection.get_all_network_interfaces(eni_id)
@ -282,20 +276,20 @@ def modify_eni(connection, module):
except BotoServerError as e: except BotoServerError as e:
print e print e
module.fail_json(msg=get_error_message(e.args[2])) module.fail_json(msg=get_error_message(e.args[2]))
eni.update() eni.update()
module.exit_json(changed=changed, interface=get_eni_info(eni)) module.exit_json(changed=changed, interface=get_eni_info(eni))
def delete_eni(connection, module): def delete_eni(connection, module):
eni_id = module.params.get("eni_id") eni_id = module.params.get("eni_id")
force_detach = module.params.get("force_detach") force_detach = module.params.get("force_detach")
try: try:
eni_result_set = connection.get_all_network_interfaces(eni_id) eni_result_set = connection.get_all_network_interfaces(eni_id)
eni = eni_result_set[0] eni = eni_result_set[0]
if force_detach is True: if force_detach is True:
if eni.attachment is not None: if eni.attachment is not None:
eni.detach(force_detach) eni.detach(force_detach)
@ -307,7 +301,7 @@ def delete_eni(connection, module):
else: else:
eni.delete() eni.delete()
changed = True changed = True
module.exit_json(changed=changed) module.exit_json(changed=changed)
except BotoServerError as e: except BotoServerError as e:
msg = get_error_message(e.args[2]) msg = get_error_message(e.args[2])
@ -316,35 +310,35 @@ def delete_eni(connection, module):
module.exit_json(changed=False) module.exit_json(changed=False)
else: else:
module.fail_json(msg=get_error_message(e.args[2])) module.fail_json(msg=get_error_message(e.args[2]))
def compare_eni(connection, module): def compare_eni(connection, module):
eni_id = module.params.get("eni_id") eni_id = module.params.get("eni_id")
subnet_id = module.params.get('subnet_id') subnet_id = module.params.get('subnet_id')
private_ip_address = module.params.get('private_ip_address') private_ip_address = module.params.get('private_ip_address')
description = module.params.get('description') description = module.params.get('description')
security_groups = module.params.get('security_groups') security_groups = module.params.get('security_groups')
try: try:
all_eni = connection.get_all_network_interfaces(eni_id) all_eni = connection.get_all_network_interfaces(eni_id)
for eni in all_eni: for eni in all_eni:
remote_security_groups = get_sec_group_list(eni.groups) remote_security_groups = get_sec_group_list(eni.groups)
if (eni.subnet_id == subnet_id) and (eni.private_ip_address == private_ip_address) and (eni.description == description) and (remote_security_groups == security_groups): if (eni.subnet_id == subnet_id) and (eni.private_ip_address == private_ip_address) and (eni.description == description) and (remote_security_groups == security_groups):
return eni return eni
except BotoServerError as e: except BotoServerError as e:
module.fail_json(msg=get_error_message(e.args[2])) module.fail_json(msg=get_error_message(e.args[2]))
return None return None
def get_sec_group_list(groups): def get_sec_group_list(groups):
# Build list of remote security groups # Build list of remote security groups
remote_security_groups = [] remote_security_groups = []
for group in groups: for group in groups:
remote_security_groups.append(group.id.encode()) remote_security_groups.append(group.id.encode())
return remote_security_groups return remote_security_groups
@ -357,7 +351,7 @@ def main():
private_ip_address = dict(), private_ip_address = dict(),
subnet_id = dict(), subnet_id = dict(),
description = dict(), description = dict(),
security_groups = dict(type='list'), security_groups = dict(type='list'),
device_index = dict(default=0, type='int'), device_index = dict(default=0, type='int'),
state = dict(default='present', choices=['present', 'absent']), state = dict(default='present', choices=['present', 'absent']),
force_detach = dict(default='no', type='bool'), force_detach = dict(default='no', type='bool'),
@ -365,18 +359,18 @@ def main():
delete_on_termination = dict(default=None, type='bool') delete_on_termination = dict(default=None, type='bool')
) )
) )
module = AnsibleModule(argument_spec=argument_spec) module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO: if not HAS_BOTO:
module.fail_json(msg='boto required for this module') module.fail_json(msg='boto required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module) region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region: if region:
try: try:
connection = connect_to_aws(boto.ec2, region, **aws_connect_params) connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")
@ -395,12 +389,13 @@ def main():
if eni_id is None: if eni_id is None:
module.fail_json(msg="eni_id must be specified") module.fail_json(msg="eni_id must be specified")
else: else:
delete_eni(connection, module) delete_eni(connection, module)
from ansible.module_utils.basic import * from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import * from ansible.module_utils.ec2 import *
# this is magic, see lib/ansible/module_common.py # this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>> #<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main() if __name__ == '__main__':
main()

@ -113,7 +113,7 @@ def main():
if region: if region:
try: try:
connection = connect_to_aws(boto.ec2, region, **aws_connect_params) connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")

@ -44,12 +44,12 @@ EXAMPLES = '''
filters: filters:
instance-state-name: running instance-state-name: running
"tag:Name": Example "tag:Name": Example
# Gather facts about instance i-123456 # Gather facts about instance i-123456
- ec2_remote_facts: - ec2_remote_facts:
filters: filters:
instance-id: i-123456 instance-id: i-123456
# Gather facts about all instances in vpc-123456 that are t2.small type # Gather facts about all instances in vpc-123456 that are t2.small type
- ec2_remote_facts: - ec2_remote_facts:
filters: filters:
@ -66,23 +66,23 @@ except ImportError:
HAS_BOTO = False HAS_BOTO = False
def get_instance_info(instance): def get_instance_info(instance):
# Get groups # Get groups
groups = [] groups = []
for group in instance.groups: for group in instance.groups:
groups.append({ 'id': group.id, 'name': group.name }.copy()) groups.append({ 'id': group.id, 'name': group.name }.copy())
# Get interfaces # Get interfaces
interfaces = [] interfaces = []
for interface in instance.interfaces: for interface in instance.interfaces:
interfaces.append({ 'id': interface.id, 'mac_address': interface.mac_address }.copy()) interfaces.append({ 'id': interface.id, 'mac_address': interface.mac_address }.copy())
# If an instance is terminated, sourceDestCheck is no longer returned # If an instance is terminated, sourceDestCheck is no longer returned
try: try:
source_dest_check = instance.sourceDestCheck source_dest_check = instance.sourceDestCheck
except AttributeError: except AttributeError:
source_dest_check = None source_dest_check = None
instance_info = { 'id': instance.id, instance_info = { 'id': instance.id,
'kernel': instance.kernel, 'kernel': instance.kernel,
'instance_profile': instance.instance_profile, 'instance_profile': instance.instance_profile,
@ -118,23 +118,23 @@ def get_instance_info(instance):
} }
return instance_info return instance_info
def list_ec2_instances(connection, module): def list_ec2_instances(connection, module):
filters = module.params.get("filters") filters = module.params.get("filters")
instance_dict_array = [] instance_dict_array = []
try: try:
all_instances = connection.get_only_instances(filters=filters) all_instances = connection.get_only_instances(filters=filters)
except BotoServerError as e: except BotoServerError as e:
module.fail_json(msg=e.message) module.fail_json(msg=e.message)
for instance in all_instances: for instance in all_instances:
instance_dict_array.append(get_instance_info(instance)) instance_dict_array.append(get_instance_info(instance))
module.exit_json(instances=instance_dict_array) module.exit_json(instances=instance_dict_array)
def main(): def main():
argument_spec = ec2_argument_spec() argument_spec = ec2_argument_spec()
@ -154,11 +154,11 @@ def main():
if region: if region:
try: try:
connection = connect_to_aws(boto.ec2, region, **aws_connect_params) connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")
list_ec2_instances(connection, module) list_ec2_instances(connection, module)
# import module snippets # import module snippets
@ -167,4 +167,3 @@ from ansible.module_utils.ec2 import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -134,7 +134,7 @@ def main():
if region: if region:
try: try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params) connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")

@ -99,7 +99,7 @@ EXAMPLES = '''
- dest: 0.0.0.0/0 - dest: 0.0.0.0/0
instance_id: "{{ nat.instance_id }}" instance_id: "{{ nat.instance_id }}"
register: nat_route_table register: nat_route_table
''' '''
@ -253,23 +253,23 @@ def get_route_table_by_id(vpc_conn, vpc_id, route_table_id):
route_tables = vpc_conn.get_all_route_tables(route_table_ids=[route_table_id], filters={'vpc_id': vpc_id}) route_tables = vpc_conn.get_all_route_tables(route_table_ids=[route_table_id], filters={'vpc_id': vpc_id})
if route_tables: if route_tables:
route_table = route_tables[0] route_table = route_tables[0]
return route_table return route_table
def get_route_table_by_tags(vpc_conn, vpc_id, tags): def get_route_table_by_tags(vpc_conn, vpc_id, tags):
count = 0 count = 0
route_table = None route_table = None
route_tables = vpc_conn.get_all_route_tables(filters={'vpc_id': vpc_id}) route_tables = vpc_conn.get_all_route_tables(filters={'vpc_id': vpc_id})
for table in route_tables: for table in route_tables:
this_tags = get_resource_tags(vpc_conn, table.id) this_tags = get_resource_tags(vpc_conn, table.id)
if tags_match(tags, this_tags): if tags_match(tags, this_tags):
route_table = table route_table = table
count +=1 count +=1
if count > 1: if count > 1:
raise RuntimeError("Tags provided do not identify a unique route table") raise RuntimeError("Tags provided do not identify a unique route table")
else: else:
return route_table return route_table
@ -463,7 +463,7 @@ def create_route_spec(connection, routes, vpc_id):
return routes return routes
def ensure_route_table_present(connection, module): def ensure_route_table_present(connection, module):
lookup = module.params.get('lookup') lookup = module.params.get('lookup')
propagating_vgw_ids = module.params.get('propagating_vgw_ids', []) propagating_vgw_ids = module.params.get('propagating_vgw_ids', [])
route_table_id = module.params.get('route_table_id') route_table_id = module.params.get('route_table_id')
@ -475,7 +475,7 @@ def ensure_route_table_present(connection, module):
routes = create_route_spec(connection, module.params.get('routes'), vpc_id) routes = create_route_spec(connection, module.params.get('routes'), vpc_id)
except AnsibleIgwSearchException as e: except AnsibleIgwSearchException as e:
module.fail_json(msg=e[0]) module.fail_json(msg=e[0])
changed = False changed = False
tags_valid = False tags_valid = False
@ -494,7 +494,7 @@ def ensure_route_table_present(connection, module):
route_table = get_route_table_by_id(connection, vpc_id, route_table_id) route_table = get_route_table_by_id(connection, vpc_id, route_table_id)
except EC2ResponseError as e: except EC2ResponseError as e:
module.fail_json(msg=e.message) module.fail_json(msg=e.message)
# If no route table returned then create new route table # If no route table returned then create new route table
if route_table is None: if route_table is None:
try: try:
@ -505,7 +505,7 @@ def ensure_route_table_present(connection, module):
module.exit_json(changed=True) module.exit_json(changed=True)
module.fail_json(msg=e.message) module.fail_json(msg=e.message)
if routes is not None: if routes is not None:
try: try:
result = ensure_routes(connection, route_table, routes, propagating_vgw_ids, check_mode) result = ensure_routes(connection, route_table, routes, propagating_vgw_ids, check_mode)
@ -560,18 +560,18 @@ def main():
vpc_id = dict(default=None, required=True) vpc_id = dict(default=None, required=True)
) )
) )
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_BOTO: if not HAS_BOTO:
module.fail_json(msg='boto is required for this module') module.fail_json(msg='boto is required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module) region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region: if region:
try: try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params) connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")
@ -598,4 +598,3 @@ from ansible.module_utils.ec2 import * # noqa
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -111,7 +111,7 @@ def main():
if region: if region:
try: try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params) connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")

@ -71,7 +71,7 @@ EXAMPLES = '''
state: absent state: absent
vpc_id: vpc-123456 vpc_id: vpc-123456
cidr: 10.0.1.16/28 cidr: 10.0.1.16/28
''' '''
import sys # noqa import sys # noqa
@ -143,7 +143,7 @@ def create_subnet(vpc_conn, vpc_id, cidr, az, check_mode):
if e.error_code == "DryRunOperation": if e.error_code == "DryRunOperation":
subnet = None subnet = None
else: else:
raise AnsibleVPCSubnetCreationException( raise AnsibleVPCSubnetCreationException(
'Unable to create subnet {0}, error: {1}'.format(cidr, e)) 'Unable to create subnet {0}, error: {1}'.format(cidr, e))
return subnet return subnet
@ -242,7 +242,7 @@ def main():
if region: if region:
try: try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params) connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")
@ -270,4 +270,3 @@ from ansible.module_utils.ec2 import * # noqa
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -111,7 +111,7 @@ def main():
if region: if region:
try: try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params) connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")

@ -25,7 +25,7 @@ description:
- Creates or terminates ecs clusters. - Creates or terminates ecs clusters.
version_added: "2.0" version_added: "2.0"
author: Mark Chance(@Java1Guy) author: Mark Chance(@Java1Guy)
requirements: [ json, time, boto, boto3 ] requirements: [ boto, boto3 ]
options: options:
state: state:
description: description:
@ -100,8 +100,9 @@ status:
returned: ACTIVE returned: ACTIVE
type: string type: string
''' '''
import time
try: try:
import json, time
import boto import boto
HAS_BOTO = True HAS_BOTO = True
except ImportError: except ImportError:
@ -147,7 +148,7 @@ class EcsClusterManager:
c = self.find_in_array(response['clusters'], cluster_name) c = self.find_in_array(response['clusters'], cluster_name)
if c: if c:
return c return c
raise StandardError("Unknown problem describing cluster %s." % cluster_name) raise Exception("Unknown problem describing cluster %s." % cluster_name)
def create_cluster(self, clusterName = 'default'): def create_cluster(self, clusterName = 'default'):
response = self.ecs.create_cluster(clusterName=clusterName) response = self.ecs.create_cluster(clusterName=clusterName)
@ -170,12 +171,10 @@ def main():
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_together=required_together) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_together=required_together)
if not HAS_BOTO: if not HAS_BOTO:
module.fail_json(msg='boto is required.') module.fail_json(msg='boto is required.')
if not HAS_BOTO3: if not HAS_BOTO3:
module.fail_json(msg='boto3 is required.') module.fail_json(msg='boto3 is required.')
cluster_name = module.params['name']
cluster_mgr = EcsClusterManager(module) cluster_mgr = EcsClusterManager(module)
try: try:

@ -94,7 +94,7 @@ EXAMPLES = '''
prefix: /logs/ prefix: /logs/
status: enabled status: enabled
state: present state: present
# Configure a lifecycle rule to transition all items with a prefix of /logs/ to glacier after 7 days and then delete after 90 days # Configure a lifecycle rule to transition all items with a prefix of /logs/ to glacier after 7 days and then delete after 90 days
- s3_lifecycle: - s3_lifecycle:
name: mybucket name: mybucket
@ -103,7 +103,7 @@ EXAMPLES = '''
prefix: /logs/ prefix: /logs/
status: enabled status: enabled
state: present state: present
# Configure a lifecycle rule to transition all items with a prefix of /logs/ to glacier on 31 Dec 2020 and then delete on 31 Dec 2030. Note that midnight GMT must be specified. # Configure a lifecycle rule to transition all items with a prefix of /logs/ to glacier on 31 Dec 2020 and then delete on 31 Dec 2030. Note that midnight GMT must be specified.
# Be sure to quote your date strings # Be sure to quote your date strings
- s3_lifecycle: - s3_lifecycle:
@ -113,20 +113,20 @@ EXAMPLES = '''
prefix: /logs/ prefix: /logs/
status: enabled status: enabled
state: present state: present
# Disable the rule created above # Disable the rule created above
- s3_lifecycle: - s3_lifecycle:
name: mybucket name: mybucket
prefix: /logs/ prefix: /logs/
status: disabled status: disabled
state: present state: present
# Delete the lifecycle rule created above # Delete the lifecycle rule created above
- s3_lifecycle: - s3_lifecycle:
name: mybucket name: mybucket
prefix: /logs/ prefix: /logs/
state: absent state: absent
''' '''
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
@ -182,7 +182,7 @@ def create_lifecycle_rule(connection, module):
expiration_obj = Expiration(date=expiration_date) expiration_obj = Expiration(date=expiration_date)
else: else:
expiration_obj = None expiration_obj = None
# Create transition # Create transition
if transition_days is not None: if transition_days is not None:
transition_obj = Transition(days=transition_days, storage_class=storage_class.upper()) transition_obj = Transition(days=transition_days, storage_class=storage_class.upper())
@ -232,7 +232,7 @@ def create_lifecycle_rule(connection, module):
bucket.configure_lifecycle(lifecycle_obj) bucket.configure_lifecycle(lifecycle_obj)
except S3ResponseError, e: except S3ResponseError, e:
module.fail_json(msg=e.message) module.fail_json(msg=e.message)
module.exit_json(changed=changed) module.exit_json(changed=changed)
def compare_rule(rule_a, rule_b): def compare_rule(rule_a, rule_b):
@ -306,7 +306,7 @@ def destroy_lifecycle_rule(connection, module):
# Create lifecycle # Create lifecycle
lifecycle_obj = Lifecycle() lifecycle_obj = Lifecycle()
# Check if rule exists # Check if rule exists
# If an ID exists, use that otherwise compare based on prefix # If an ID exists, use that otherwise compare based on prefix
if rule_id is not None: if rule_id is not None:
@ -323,8 +323,7 @@ def destroy_lifecycle_rule(connection, module):
changed = True changed = True
else: else:
lifecycle_obj.append(existing_rule) lifecycle_obj.append(existing_rule)
# Write lifecycle to bucket or, if there no rules left, delete lifecycle configuration # Write lifecycle to bucket or, if there no rules left, delete lifecycle configuration
try: try:
if lifecycle_obj: if lifecycle_obj:
@ -333,9 +332,9 @@ def destroy_lifecycle_rule(connection, module):
bucket.delete_lifecycle_configuration() bucket.delete_lifecycle_configuration()
except BotoServerError, e: except BotoServerError, e:
module.fail_json(msg=e.message) module.fail_json(msg=e.message)
module.exit_json(changed=changed) module.exit_json(changed=changed)
def main(): def main():
@ -361,18 +360,18 @@ def main():
[ 'expiration_days', 'expiration_date' ], [ 'expiration_days', 'expiration_date' ],
[ 'expiration_days', 'transition_date' ], [ 'expiration_days', 'transition_date' ],
[ 'transition_days', 'transition_date' ], [ 'transition_days', 'transition_date' ],
[ 'transition_days', 'expiration_date' ] [ 'transition_days', 'expiration_date' ]
] ]
) )
if not HAS_BOTO: if not HAS_BOTO:
module.fail_json(msg='boto required for this module') module.fail_json(msg='boto required for this module')
if not HAS_DATEUTIL: if not HAS_DATEUTIL:
module.fail_json(msg='dateutil required for this module') module.fail_json(msg='dateutil required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module) region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region in ('us-east-1', '', None): if region in ('us-east-1', '', None):
# S3ism for the US Standard region # S3ism for the US Standard region
location = Location.DEFAULT location = Location.DEFAULT
@ -385,7 +384,7 @@ def main():
# use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases # use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases
if connection is None: if connection is None:
connection = boto.connect_s3(**aws_connect_params) connection = boto.connect_s3(**aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
expiration_date = module.params.get("expiration_date") expiration_date = module.params.get("expiration_date")
@ -398,13 +397,13 @@ def main():
datetime.datetime.strptime(expiration_date, "%Y-%m-%dT%H:%M:%S.000Z") datetime.datetime.strptime(expiration_date, "%Y-%m-%dT%H:%M:%S.000Z")
except ValueError, e: except ValueError, e:
module.fail_json(msg="expiration_date is not a valid ISO-8601 format. The time must be midnight and a timezone of GMT must be included") module.fail_json(msg="expiration_date is not a valid ISO-8601 format. The time must be midnight and a timezone of GMT must be included")
if transition_date is not None: if transition_date is not None:
try: try:
datetime.datetime.strptime(transition_date, "%Y-%m-%dT%H:%M:%S.000Z") datetime.datetime.strptime(transition_date, "%Y-%m-%dT%H:%M:%S.000Z")
except ValueError, e: except ValueError, e:
module.fail_json(msg="expiration_date is not a valid ISO-8601 format. The time must be midnight and a timezone of GMT must be included") module.fail_json(msg="expiration_date is not a valid ISO-8601 format. The time must be midnight and a timezone of GMT must be included")
if state == 'present': if state == 'present':
create_lifecycle_rule(connection, module) create_lifecycle_rule(connection, module)
elif state == 'absent': elif state == 'absent':

@ -61,7 +61,7 @@ EXAMPLES = '''
s3_logging: s3_logging:
name: mywebsite.com name: mywebsite.com
state: absent state: absent
''' '''
try: try:
@ -74,21 +74,21 @@ except ImportError:
def compare_bucket_logging(bucket, target_bucket, target_prefix): def compare_bucket_logging(bucket, target_bucket, target_prefix):
bucket_log_obj = bucket.get_logging_status() bucket_log_obj = bucket.get_logging_status()
if bucket_log_obj.target != target_bucket or bucket_log_obj.prefix != target_prefix: if bucket_log_obj.target != target_bucket or bucket_log_obj.prefix != target_prefix:
return False return False
else: else:
return True return True
def enable_bucket_logging(connection, module): def enable_bucket_logging(connection, module):
bucket_name = module.params.get("name") bucket_name = module.params.get("name")
target_bucket = module.params.get("target_bucket") target_bucket = module.params.get("target_bucket")
target_prefix = module.params.get("target_prefix") target_prefix = module.params.get("target_prefix")
changed = False changed = False
try: try:
bucket = connection.get_bucket(bucket_name) bucket = connection.get_bucket(bucket_name)
except S3ResponseError as e: except S3ResponseError as e:
@ -111,15 +111,15 @@ def enable_bucket_logging(connection, module):
except S3ResponseError as e: except S3ResponseError as e:
module.fail_json(msg=e.message) module.fail_json(msg=e.message)
module.exit_json(changed=changed) module.exit_json(changed=changed)
def disable_bucket_logging(connection, module): def disable_bucket_logging(connection, module):
bucket_name = module.params.get("name") bucket_name = module.params.get("name")
changed = False changed = False
try: try:
bucket = connection.get_bucket(bucket_name) bucket = connection.get_bucket(bucket_name)
if not compare_bucket_logging(bucket, None, None): if not compare_bucket_logging(bucket, None, None):
@ -127,12 +127,12 @@ def disable_bucket_logging(connection, module):
changed = True changed = True
except S3ResponseError as e: except S3ResponseError as e:
module.fail_json(msg=e.message) module.fail_json(msg=e.message)
module.exit_json(changed=changed) module.exit_json(changed=changed)
def main(): def main():
argument_spec = ec2_argument_spec() argument_spec = ec2_argument_spec()
argument_spec.update( argument_spec.update(
dict( dict(
@ -142,16 +142,16 @@ def main():
state = dict(required=False, default='present', choices=['present', 'absent']) state = dict(required=False, default='present', choices=['present', 'absent'])
) )
) )
module = AnsibleModule(argument_spec=argument_spec) module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO: if not HAS_BOTO:
module.fail_json(msg='boto required for this module') module.fail_json(msg='boto required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module) region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region in ('us-east-1', '', None): if region in ('us-east-1', '', None):
# S3ism for the US Standard region # S3ism for the US Standard region
location = Location.DEFAULT location = Location.DEFAULT
else: else:
# Boto uses symbolic names for locations but region strings will # Boto uses symbolic names for locations but region strings will
@ -162,10 +162,9 @@ def main():
# use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases # use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases
if connection is None: if connection is None:
connection = boto.connect_s3(**aws_connect_params) connection = boto.connect_s3(**aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
state = module.params.get("state") state = module.params.get("state")
if state == 'present': if state == 'present':

@ -215,8 +215,8 @@ def main():
try: try:
connection = connect_to_aws(boto.sqs, region, **aws_connect_params) connection = connect_to_aws(boto.sqs, region, **aws_connect_params)
except (NoAuthHandlerFound, StandardError), e: except (NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
state = module.params.get('state') state = module.params.get('state')
@ -230,4 +230,5 @@ def main():
from ansible.module_utils.basic import * from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import * from ansible.module_utils.ec2 import *
main() if __name__ == '__main__':
main()

@ -16,7 +16,7 @@
DOCUMENTATION = ''' DOCUMENTATION = '''
--- ---
module: sts_assume_role module: sts_assume_role
short_description: Assume a role using AWS Security Token Service and obtain temporary credentials short_description: Assume a role using AWS Security Token Service and obtain temporary credentials
description: description:
- Assume a role using AWS Security Token Service and obtain temporary credentials - Assume a role using AWS Security Token Service and obtain temporary credentials
@ -25,7 +25,7 @@ author: Boris Ekelchik (@bekelchik)
options: options:
role_arn: role_arn:
description: description:
- The Amazon Resource Name (ARN) of the role that the caller is assuming (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs) - The Amazon Resource Name (ARN) of the role that the caller is assuming (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs)
required: true required: true
role_session_name: role_session_name:
description: description:
@ -33,27 +33,27 @@ options:
required: true required: true
policy: policy:
description: description:
- Supplemental policy to use in addition to assumed role's policies. - Supplemental policy to use in addition to assumed role's policies.
required: false required: false
default: null default: null
duration_seconds: duration_seconds:
description: description:
- The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set to 3600 seconds. - The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set to 3600 seconds.
required: false required: false
default: null default: null
external_id: external_id:
description: description:
- A unique identifier that is used by third parties to assume a role in their customers' accounts. - A unique identifier that is used by third parties to assume a role in their customers' accounts.
required: false required: false
default: null default: null
mfa_serial_number: mfa_serial_number:
description: description:
- he identification number of the MFA device that is associated with the user who is making the AssumeRole call. - he identification number of the MFA device that is associated with the user who is making the AssumeRole call.
required: false required: false
default: null default: null
mfa_token: mfa_token:
description: description:
- The value provided by the MFA device, if the trust policy of the role being assumed requires MFA. - The value provided by the MFA device, if the trust policy of the role being assumed requires MFA.
required: false required: false
default: null default: null
notes: notes:
@ -67,12 +67,12 @@ EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details. # Note: These examples do not set authentication details, see the AWS Guide for details.
# Assume an existing role (more details: http://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) # Assume an existing role (more details: http://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html)
sts_assume_role: sts_assume_role:
role_arn: "arn:aws:iam::123456789012:role/someRole" role_arn: "arn:aws:iam::123456789012:role/someRole"
session_name: "someRoleSession" session_name: "someRoleSession"
register: assumed_role register: assumed_role
# Use the assumed role above to tag an instance in account 123456789012 # Use the assumed role above to tag an instance in account 123456789012
ec2_tag: ec2_tag:
aws_access_key: "{{ assumed_role.sts_creds.access_key }}" aws_access_key: "{{ assumed_role.sts_creds.access_key }}"
aws_secret_key: "{{ assumed_role.sts_creds.secret_key }}" aws_secret_key: "{{ assumed_role.sts_creds.secret_key }}"
@ -84,19 +84,16 @@ ec2_tag:
''' '''
import sys
import time
try: try:
import boto.sts import boto.sts
from boto.exception import BotoServerError from boto.exception import BotoServerError
HAS_BOTO = True HAS_BOTO = True
except ImportError: except ImportError:
HAS_BOTO = False HAS_BOTO = False
def assume_role_policy(connection, module): def assume_role_policy(connection, module):
role_arn = module.params.get('role_arn') role_arn = module.params.get('role_arn')
role_session_name = module.params.get('role_session_name') role_session_name = module.params.get('role_session_name')
policy = module.params.get('policy') policy = module.params.get('policy')
@ -105,13 +102,13 @@ def assume_role_policy(connection, module):
mfa_serial_number = module.params.get('mfa_serial_number') mfa_serial_number = module.params.get('mfa_serial_number')
mfa_token = module.params.get('mfa_token') mfa_token = module.params.get('mfa_token')
changed = False changed = False
try: try:
assumed_role = connection.assume_role(role_arn, role_session_name, policy, duration_seconds, external_id, mfa_serial_number, mfa_token) assumed_role = connection.assume_role(role_arn, role_session_name, policy, duration_seconds, external_id, mfa_serial_number, mfa_token)
changed = True changed = True
except BotoServerError, e: except BotoServerError, e:
module.fail_json(msg=e) module.fail_json(msg=e)
module.exit_json(changed=changed, sts_creds=assumed_role.credentials.__dict__, sts_user=assumed_role.user.__dict__) module.exit_json(changed=changed, sts_creds=assumed_role.credentials.__dict__, sts_user=assumed_role.user.__dict__)
def main(): def main():
@ -127,18 +124,18 @@ def main():
mfa_token = dict(required=False, default=None) mfa_token = dict(required=False, default=None)
) )
) )
module = AnsibleModule(argument_spec=argument_spec) module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO: if not HAS_BOTO:
module.fail_json(msg='boto required for this module') module.fail_json(msg='boto required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module) region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region: if region:
try: try:
connection = connect_to_aws(boto.sts, region, **aws_connect_params) connection = connect_to_aws(boto.sts, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e: except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
else: else:
module.fail_json(msg="region must be specified") module.fail_json(msg="region must be specified")
@ -147,10 +144,11 @@ def main():
assume_role_policy(connection, module) assume_role_policy(connection, module)
except BotoServerError, e: except BotoServerError, e:
module.fail_json(msg=e) module.fail_json(msg=e)
# import module snippets # import module snippets
from ansible.module_utils.basic import * from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import * from ansible.module_utils.ec2 import *
main() if __name__ == '__main__':
main()

Loading…
Cancel
Save