From 5bd1bcaa2db8e6154d7a6fdcbd94c6bbb017cca5 Mon Sep 17 00:00:00 2001 From: Toshio Kuratomi Date: Mon, 30 Nov 2015 19:01:57 -0800 Subject: [PATCH] Don't raise or catch StandardError in amazon modules --- .../extras/cloud/amazon/dynamodb_table.py | 3 +- .../extras/cloud/amazon/ec2_elb_facts.py | 5 +- .../modules/extras/cloud/amazon/ec2_eni.py | 99 +++++++++---------- .../extras/cloud/amazon/ec2_eni_facts.py | 2 +- .../extras/cloud/amazon/ec2_remote_facts.py | 33 +++---- .../extras/cloud/amazon/ec2_vpc_igw.py | 2 +- .../cloud/amazon/ec2_vpc_route_table.py | 31 +++--- .../cloud/amazon/ec2_vpc_route_table_facts.py | 2 +- .../extras/cloud/amazon/ec2_vpc_subnet.py | 20 ++-- .../cloud/amazon/ec2_vpc_subnet_facts.py | 2 +- .../extras/cloud/amazon/ecs_cluster.py | 14 +-- .../extras/cloud/amazon/s3_lifecycle.py | 37 ++++--- .../modules/extras/cloud/amazon/s3_logging.py | 37 ++++--- .../modules/extras/cloud/amazon/sqs_queue.py | 7 +- .../extras/cloud/amazon/sts_assume_role.py | 46 +++++---- 15 files changed, 164 insertions(+), 176 deletions(-) diff --git a/lib/ansible/modules/extras/cloud/amazon/dynamodb_table.py b/lib/ansible/modules/extras/cloud/amazon/dynamodb_table.py index 29ba230fe48..fb1d3cf40d8 100644 --- a/lib/ansible/modules/extras/cloud/amazon/dynamodb_table.py +++ b/lib/ansible/modules/extras/cloud/amazon/dynamodb_table.py @@ -272,8 +272,7 @@ def main(): try: connection = connect_to_aws(boto.dynamodb2, region, **aws_connect_params) - - except (NoAuthHandlerFound, StandardError), e: + except (NoAuthHandlerFound, AnsibleAWSError), e: module.fail_json(msg=str(e)) state = module.params.get('state') diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_elb_facts.py b/lib/ansible/modules/extras/cloud/amazon/ec2_elb_facts.py index 554b75c951d..8170397c804 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_elb_facts.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_elb_facts.py @@ -182,7 +182,7 @@ def main(): if region: try: 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)) else: module.fail_json(msg="region must be specified") @@ -192,4 +192,5 @@ def main(): from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * -main() +if __name__ == '__main__': + main() diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_eni.py b/lib/ansible/modules/extras/cloud/amazon/ec2_eni.py index 59a26291388..94fd48bfd6b 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_eni.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_eni.py @@ -94,25 +94,25 @@ EXAMPLES = ''' private_ip_address: 172.31.0.20 subnet_id: subnet-xxxxxxxx state: present - + # Destroy an ENI, detaching it from any instance if necessary - ec2_eni: eni_id: eni-xxxxxxx force_detach: yes state: absent - + # Update an ENI - ec2_eni: eni_id: eni-xxxxxxx description: "My new description" state: present - + # Detach an ENI from an instance - ec2_eni: eni_id: eni-xxxxxxx instance_id: None state: present - + ### Delete an interface on termination # First create the interface - ec2_eni: @@ -122,7 +122,7 @@ EXAMPLES = ''' subnet_id: subnet-xxxxxxxx state: present register: eni - + # Modify the interface to enable the delete_on_terminaton flag - ec2_eni: eni_id: {{ "eni.interface.id" }} @@ -143,14 +143,14 @@ except ImportError: def get_error_message(xml_string): - + root = ET.fromstring(xml_string) - for message in root.findall('.//Message'): + for message in root.findall('.//Message'): return message.text - - + + def get_eni_info(interface): - + interface_info = {'id': interface.id, 'subnet_id': interface.subnet_id, 'vpc_id': interface.vpc_id, @@ -162,7 +162,7 @@ def get_eni_info(interface): 'source_dest_check': interface.source_dest_check, 'groups': dict((group.id, group.name) for group in interface.groups), } - + if interface.attachment is not None: interface_info['attachment'] = {'attachment_id': interface.attachment.id, 'instance_id': interface.attachment.instance_id, @@ -171,11 +171,11 @@ def get_eni_info(interface): 'attach_time': interface.attachment.attach_time, 'delete_on_termination': interface.attachment.delete_on_termination, } - + return interface_info - + def wait_for_eni(eni, status): - + while True: time.sleep(3) eni.update() @@ -186,23 +186,20 @@ def wait_for_eni(eni, status): else: if status == "attached" and eni.attachment.status == "attached": break - - + + def create_eni(connection, module): - + instance_id = module.params.get("instance_id") if instance_id == 'None': instance_id = None - do_detach = True - else: - do_detach = False 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') security_groups = module.params.get('security_groups') changed = False - + try: eni = compare_eni(connection, module) if eni is None: @@ -210,22 +207,22 @@ def create_eni(connection, module): if instance_id is not None: try: eni.attach(instance_id, device_index) - except BotoServerError as ex: + except BotoServerError: eni.delete() raise # Wait to allow creation / attachment to finish wait_for_eni(eni, "attached") eni.update() changed = True - + except BotoServerError as e: module.fail_json(msg=get_error_message(e.args[2])) - + module.exit_json(changed=changed, interface=get_eni_info(eni)) - + def modify_eni(connection, module): - + eni_id = module.params.get("eni_id") instance_id = module.params.get("instance_id") if instance_id == 'None': @@ -234,8 +231,6 @@ def modify_eni(connection, module): else: do_detach = False 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') security_groups = module.params.get('security_groups') force_detach = module.params.get("force_detach") @@ -243,7 +238,6 @@ def modify_eni(connection, module): delete_on_termination = module.params.get("delete_on_termination") changed = False - try: # Get the eni with the eni_id specified eni_result_set = connection.get_all_network_interfaces(eni_id) @@ -280,20 +274,20 @@ def modify_eni(connection, module): except BotoServerError as e: print e module.fail_json(msg=get_error_message(e.args[2])) - + eni.update() module.exit_json(changed=changed, interface=get_eni_info(eni)) - - + + def delete_eni(connection, module): - + eni_id = module.params.get("eni_id") force_detach = module.params.get("force_detach") - + try: eni_result_set = connection.get_all_network_interfaces(eni_id) eni = eni_result_set[0] - + if force_detach is True: if eni.attachment is not None: eni.detach(force_detach) @@ -305,7 +299,7 @@ def delete_eni(connection, module): else: eni.delete() changed = True - + module.exit_json(changed=changed) except BotoServerError as e: msg = get_error_message(e.args[2]) @@ -314,35 +308,35 @@ def delete_eni(connection, module): module.exit_json(changed=False) else: module.fail_json(msg=get_error_message(e.args[2])) - + def compare_eni(connection, module): - + eni_id = module.params.get("eni_id") subnet_id = module.params.get('subnet_id') private_ip_address = module.params.get('private_ip_address') description = module.params.get('description') security_groups = module.params.get('security_groups') - + try: all_eni = connection.get_all_network_interfaces(eni_id) for eni in all_eni: 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 - + except BotoServerError as e: module.fail_json(msg=get_error_message(e.args[2])) - + return None def get_sec_group_list(groups): - + # Build list of remote security groups remote_security_groups = [] for group in groups: remote_security_groups.append(group.id.encode()) - + return remote_security_groups @@ -355,7 +349,7 @@ def main(): private_ip_address = dict(), subnet_id = dict(), description = dict(), - security_groups = dict(type='list'), + security_groups = dict(type='list'), device_index = dict(default=0, type='int'), state = dict(default='present', choices=['present', 'absent']), force_detach = dict(default='no', type='bool'), @@ -363,18 +357,18 @@ def main(): delete_on_termination = dict(default=None, type='bool') ) ) - + module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') - + region, ec2_url, aws_connect_params = get_aws_connection_info(module) - + if region: try: 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)) else: module.fail_json(msg="region must be specified") @@ -393,12 +387,13 @@ def main(): if eni_id is None: module.fail_json(msg="eni_id must be specified") else: - delete_eni(connection, module) - + delete_eni(connection, module) + from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * # this is magic, see lib/ansible/module_common.py #<> -main() +if __name__ == '__main__': + main() diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_eni_facts.py b/lib/ansible/modules/extras/cloud/amazon/ec2_eni_facts.py index da7f9775bc3..b96f641624c 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_eni_facts.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_eni_facts.py @@ -123,7 +123,7 @@ def main(): if region: try: 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)) else: module.fail_json(msg="region must be specified") diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_remote_facts.py b/lib/ansible/modules/extras/cloud/amazon/ec2_remote_facts.py index cf54fa0274d..28fc2c97d63 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_remote_facts.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_remote_facts.py @@ -44,12 +44,12 @@ EXAMPLES = ''' filters: instance-state-name: running "tag:Name": Example - + # Gather facts about instance i-123456 - ec2_remote_facts: filters: instance-id: i-123456 - + # Gather facts about all instances in vpc-123456 that are t2.small type - ec2_remote_facts: filters: @@ -66,23 +66,23 @@ except ImportError: HAS_BOTO = False def get_instance_info(instance): - + # Get groups 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 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 try: - source_dest_check = instance.sourceDestCheck + source_dest_check = instance.sourceDestCheck except AttributeError: - source_dest_check = None - + source_dest_check = None + instance_info = { 'id': instance.id, 'kernel': instance.kernel, 'instance_profile': instance.instance_profile, @@ -118,23 +118,23 @@ def get_instance_info(instance): } return instance_info - + def list_ec2_instances(connection, module): - + filters = module.params.get("filters") instance_dict_array = [] - + try: all_instances = connection.get_only_instances(filters=filters) except BotoServerError as e: module.fail_json(msg=e.message) - + for instance in all_instances: instance_dict_array.append(get_instance_info(instance)) - + module.exit_json(instances=instance_dict_array) - + def main(): argument_spec = ec2_argument_spec() @@ -154,11 +154,11 @@ def main(): if region: try: 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)) else: module.fail_json(msg="region must be specified") - + list_ec2_instances(connection, module) # import module snippets @@ -167,4 +167,3 @@ from ansible.module_utils.ec2 import * if __name__ == '__main__': main() - diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_igw.py b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_igw.py index e374580433a..7d9900bf2da 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_igw.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_igw.py @@ -138,7 +138,7 @@ def main(): if region: try: 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)) else: module.fail_json(msg="region must be specified") diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table.py b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table.py index fcb66e21a28..b9cfa6481e2 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table.py @@ -98,7 +98,7 @@ EXAMPLES = ''' - dest: 0.0.0.0/0 instance_id: "{{ nat.instance_id }}" register: nat_route_table - + ''' @@ -252,23 +252,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}) if route_tables: route_table = route_tables[0] - + return route_table - + def get_route_table_by_tags(vpc_conn, vpc_id, tags): - + count = 0 - route_table = None + route_table = None route_tables = vpc_conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for table in route_tables: this_tags = get_resource_tags(vpc_conn, table.id) if tags_match(tags, this_tags): route_table = table count +=1 - + if count > 1: raise RuntimeError("Tags provided do not identify a unique route table") - else: + else: return route_table @@ -462,7 +462,7 @@ def create_route_spec(connection, routes, vpc_id): return routes def ensure_route_table_present(connection, module): - + lookup = module.params.get('lookup') propagating_vgw_ids = module.params.get('propagating_vgw_ids', []) route_table_id = module.params.get('route_table_id') @@ -474,7 +474,7 @@ def ensure_route_table_present(connection, module): routes = create_route_spec(connection, module.params.get('routes'), vpc_id) except AnsibleIgwSearchException as e: module.fail_json(msg=e[0]) - + changed = False tags_valid = False @@ -493,7 +493,7 @@ def ensure_route_table_present(connection, module): route_table = get_route_table_by_id(connection, vpc_id, route_table_id) except EC2ResponseError as e: module.fail_json(msg=e.message) - + # If no route table returned then create new route table if route_table is None: try: @@ -504,7 +504,7 @@ def ensure_route_table_present(connection, module): module.exit_json(changed=True) module.fail_json(msg=e.message) - + if routes is not None: try: result = ensure_routes(connection, route_table, routes, propagating_vgw_ids, check_mode) @@ -559,18 +559,18 @@ def main(): vpc_id = dict(default=None, required=True) ) ) - + module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) - + if not HAS_BOTO: module.fail_json(msg='boto is required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module) - + if region: try: 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)) else: module.fail_json(msg="region must be specified") @@ -597,4 +597,3 @@ from ansible.module_utils.ec2 import * # noqa if __name__ == '__main__': main() - diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table_facts.py b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table_facts.py index 7d37b2d79a2..d9a51f0dc0d 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table_facts.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_route_table_facts.py @@ -116,7 +116,7 @@ def main(): if region: try: 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)) else: module.fail_json(msg="region must be specified") diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet.py b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet.py index c7403660473..031f11e1a80 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet.py @@ -70,7 +70,7 @@ EXAMPLES = ''' state: absent vpc_id: vpc-123456 cidr: 10.0.1.16/28 - + ''' import sys # noqa @@ -142,7 +142,7 @@ def create_subnet(vpc_conn, vpc_id, cidr, az, check_mode): if e.error_code == "DryRunOperation": subnet = None else: - raise AnsibleVPCSubnetCreationException( + raise AnsibleVPCSubnetCreationException( 'Unable to create subnet {0}, error: {1}'.format(cidr, e)) return subnet @@ -249,14 +249,13 @@ def main(): if not region: module.fail_json(msg='Region must be specified') - try: - vpc_conn = boto.vpc.connect_to_region( - region, - aws_access_key_id=aws_access_key, - aws_secret_access_key=aws_secret_key - ) - except boto.exception.NoAuthHandlerFound as e: - module.fail_json(msg=str(e)) + if region: + try: + connection = connect_to_aws(boto.vpc, region, **aws_connect_params) + except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e: + module.fail_json(msg=str(e)) + else: + module.fail_json(msg="region must be specified") vpc_id = module.params.get('vpc_id') tags = module.params.get('tags') @@ -281,4 +280,3 @@ from ansible.module_utils.ec2 import * # noqa if __name__ == '__main__': main() - diff --git a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet_facts.py b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet_facts.py index c3c8268579a..0b4ed6d306c 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet_facts.py +++ b/lib/ansible/modules/extras/cloud/amazon/ec2_vpc_subnet_facts.py @@ -116,7 +116,7 @@ def main(): if region: try: 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)) else: module.fail_json(msg="region must be specified") diff --git a/lib/ansible/modules/extras/cloud/amazon/ecs_cluster.py b/lib/ansible/modules/extras/cloud/amazon/ecs_cluster.py index 9dc49860384..6c7a0aa3425 100644 --- a/lib/ansible/modules/extras/cloud/amazon/ecs_cluster.py +++ b/lib/ansible/modules/extras/cloud/amazon/ecs_cluster.py @@ -24,7 +24,8 @@ notes: description: - Creates or terminates ecs clusters. version_added: "2.0" -requirements: [ json, time, boto, boto3 ] +author: Mark Chance(@Java1Guy) +requirements: [ boto, boto3 ] options: state: description: @@ -97,8 +98,9 @@ status: returned: ACTIVE type: string ''' +import time + try: - import json, time import boto HAS_BOTO = True except ImportError: @@ -144,7 +146,7 @@ class EcsClusterManager: c = self.find_in_array(response['clusters'], cluster_name) if 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'): response = self.ecs.create_cluster(clusterName=clusterName) @@ -167,12 +169,10 @@ def main(): module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_together=required_together) if not HAS_BOTO: - module.fail_json(msg='boto is required.') + module.fail_json(msg='boto is required.') if not HAS_BOTO3: - module.fail_json(msg='boto3 is required.') - - cluster_name = module.params['name'] + module.fail_json(msg='boto3 is required.') cluster_mgr = EcsClusterManager(module) try: diff --git a/lib/ansible/modules/extras/cloud/amazon/s3_lifecycle.py b/lib/ansible/modules/extras/cloud/amazon/s3_lifecycle.py index 7a54365c8bd..1ebfedcaf4e 100644 --- a/lib/ansible/modules/extras/cloud/amazon/s3_lifecycle.py +++ b/lib/ansible/modules/extras/cloud/amazon/s3_lifecycle.py @@ -98,7 +98,7 @@ EXAMPLES = ''' prefix: /logs/ status: enabled 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 - s3_lifecycle: name: mybucket @@ -107,7 +107,7 @@ EXAMPLES = ''' prefix: /logs/ status: enabled 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. # Be sure to quote your date strings - s3_lifecycle: @@ -117,20 +117,20 @@ EXAMPLES = ''' prefix: /logs/ status: enabled state: present - + # Disable the rule created above - s3_lifecycle: name: mybucket prefix: /logs/ status: disabled state: present - + # Delete the lifecycle rule created above - s3_lifecycle: name: mybucket prefix: /logs/ state: absent - + ''' import xml.etree.ElementTree as ET @@ -186,7 +186,7 @@ def create_lifecycle_rule(connection, module): expiration_obj = Expiration(date=expiration_date) else: expiration_obj = None - + # Create transition if transition_days is not None: transition_obj = Transition(days=transition_days, storage_class=storage_class.upper()) @@ -236,7 +236,7 @@ def create_lifecycle_rule(connection, module): bucket.configure_lifecycle(lifecycle_obj) except S3ResponseError, e: module.fail_json(msg=e.message) - + module.exit_json(changed=changed) def compare_rule(rule_a, rule_b): @@ -310,7 +310,7 @@ def destroy_lifecycle_rule(connection, module): # Create lifecycle lifecycle_obj = Lifecycle() - + # Check if rule exists # If an ID exists, use that otherwise compare based on prefix if rule_id is not None: @@ -327,8 +327,7 @@ def destroy_lifecycle_rule(connection, module): changed = True else: lifecycle_obj.append(existing_rule) - - + # Write lifecycle to bucket or, if there no rules left, delete lifecycle configuration try: if lifecycle_obj: @@ -337,9 +336,9 @@ def destroy_lifecycle_rule(connection, module): bucket.delete_lifecycle_configuration() except BotoServerError, e: module.fail_json(msg=e.message) - + module.exit_json(changed=changed) - + def main(): @@ -365,18 +364,18 @@ def main(): [ 'expiration_days', 'expiration_date' ], [ 'expiration_days', 'transition_date' ], [ 'transition_days', 'transition_date' ], - [ 'transition_days', 'expiration_date' ] + [ 'transition_days', 'expiration_date' ] ] ) if not HAS_BOTO: module.fail_json(msg='boto required for this module') - + 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) - + if region in ('us-east-1', '', None): # S3ism for the US Standard region location = Location.DEFAULT @@ -389,7 +388,7 @@ def main(): # use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases if connection is None: 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)) expiration_date = module.params.get("expiration_date") @@ -402,13 +401,13 @@ def main(): datetime.datetime.strptime(expiration_date, "%Y-%m-%dT%H:%M:%S.000Z") 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") - + if transition_date is not None: try: datetime.datetime.strptime(transition_date, "%Y-%m-%dT%H:%M:%S.000Z") 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") - + if state == 'present': create_lifecycle_rule(connection, module) elif state == 'absent': diff --git a/lib/ansible/modules/extras/cloud/amazon/s3_logging.py b/lib/ansible/modules/extras/cloud/amazon/s3_logging.py index 75b3fe73508..cfab4c3e3e7 100644 --- a/lib/ansible/modules/extras/cloud/amazon/s3_logging.py +++ b/lib/ansible/modules/extras/cloud/amazon/s3_logging.py @@ -65,7 +65,7 @@ EXAMPLES = ''' s3_logging: name: mywebsite.com state: absent - + ''' try: @@ -78,21 +78,21 @@ except ImportError: def compare_bucket_logging(bucket, target_bucket, target_prefix): - + bucket_log_obj = bucket.get_logging_status() if bucket_log_obj.target != target_bucket or bucket_log_obj.prefix != target_prefix: return False else: return True - + def enable_bucket_logging(connection, module): - + bucket_name = module.params.get("name") target_bucket = module.params.get("target_bucket") target_prefix = module.params.get("target_prefix") changed = False - + try: bucket = connection.get_bucket(bucket_name) except S3ResponseError as e: @@ -115,15 +115,15 @@ def enable_bucket_logging(connection, module): except S3ResponseError as e: module.fail_json(msg=e.message) - + module.exit_json(changed=changed) - - + + def disable_bucket_logging(connection, module): - + bucket_name = module.params.get("name") changed = False - + try: bucket = connection.get_bucket(bucket_name) if not compare_bucket_logging(bucket, None, None): @@ -131,12 +131,12 @@ def disable_bucket_logging(connection, module): changed = True except S3ResponseError as e: module.fail_json(msg=e.message) - + module.exit_json(changed=changed) - - + + def main(): - + argument_spec = ec2_argument_spec() argument_spec.update( dict( @@ -146,16 +146,16 @@ def main(): state = dict(required=False, default='present', choices=['present', 'absent']) ) ) - + module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') - + region, ec2_url, aws_connect_params = get_aws_connection_info(module) if region in ('us-east-1', '', None): - # S3ism for the US Standard region + # S3ism for the US Standard region location = Location.DEFAULT else: # Boto uses symbolic names for locations but region strings will @@ -166,10 +166,9 @@ def main(): # use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases if connection is None: 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)) - state = module.params.get("state") if state == 'present': diff --git a/lib/ansible/modules/extras/cloud/amazon/sqs_queue.py b/lib/ansible/modules/extras/cloud/amazon/sqs_queue.py index 3febc8981f2..92a03b1f1ca 100644 --- a/lib/ansible/modules/extras/cloud/amazon/sqs_queue.py +++ b/lib/ansible/modules/extras/cloud/amazon/sqs_queue.py @@ -219,8 +219,8 @@ def main(): try: connection = connect_to_aws(boto.sqs, region, **aws_connect_params) - - except (NoAuthHandlerFound, StandardError), e: + + except (NoAuthHandlerFound, AnsibleAWSError), e: module.fail_json(msg=str(e)) state = module.params.get('state') @@ -234,4 +234,5 @@ def main(): from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * -main() +if __name__ == '__main__': + main() diff --git a/lib/ansible/modules/extras/cloud/amazon/sts_assume_role.py b/lib/ansible/modules/extras/cloud/amazon/sts_assume_role.py index 3b07b09d4c6..7f6afddc06b 100644 --- a/lib/ansible/modules/extras/cloud/amazon/sts_assume_role.py +++ b/lib/ansible/modules/extras/cloud/amazon/sts_assume_role.py @@ -16,7 +16,7 @@ DOCUMENTATION = ''' --- -module: sts_assume_role +module: sts_assume_role short_description: Assume a role using AWS Security Token Service and obtain temporary credentials description: - Assume a role using AWS Security Token Service and obtain temporary credentials @@ -25,7 +25,7 @@ author: Boris Ekelchik (@bekelchik) options: role_arn: 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 role_session_name: description: @@ -33,27 +33,27 @@ options: required: true policy: 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 default: null duration_seconds: 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 default: null external_id: 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 default: null mfa_serial_number: 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 default: null mfa_token: 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 default: null notes: @@ -65,12 +65,12 @@ EXAMPLES = ''' # 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) -sts_assume_role: +sts_assume_role: role_arn: "arn:aws:iam::123456789012:role/someRole" session_name: "someRoleSession" 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: aws_access_key: "{{ assumed_role.sts_creds.access_key }}" aws_secret_key: "{{ assumed_role.sts_creds.secret_key }}" @@ -82,19 +82,16 @@ ec2_tag: ''' -import sys -import time - try: import boto.sts from boto.exception import BotoServerError HAS_BOTO = True except ImportError: HAS_BOTO = False - + def assume_role_policy(connection, module): - + role_arn = module.params.get('role_arn') role_session_name = module.params.get('role_session_name') policy = module.params.get('policy') @@ -103,13 +100,13 @@ def assume_role_policy(connection, module): mfa_serial_number = module.params.get('mfa_serial_number') mfa_token = module.params.get('mfa_token') changed = False - + try: 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: module.fail_json(msg=e) - + module.exit_json(changed=changed, sts_creds=assumed_role.credentials.__dict__, sts_user=assumed_role.user.__dict__) def main(): @@ -125,18 +122,18 @@ def main(): mfa_token = dict(required=False, default=None) ) ) - + module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') - + region, ec2_url, aws_connect_params = get_aws_connection_info(module) - + if region: try: 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)) else: module.fail_json(msg="region must be specified") @@ -145,10 +142,11 @@ def main(): assume_role_policy(connection, module) except BotoServerError, e: module.fail_json(msg=e) - - + + # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * -main() +if __name__ == '__main__': + main()