def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( vpc_id=dict(), service=dict(), policy=dict(type='json'), policy_file=dict(type='path', aliases=['policy_path']), state=dict(default='present', choices=['present', 'absent']), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=320, required=False), route_table_ids=dict(type='list'), vpc_endpoint_id=dict(), client_token=dict(), ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[['policy', 'policy_file']], required_if=[ ['state', 'present', ['vpc_id', 'service']], ['state', 'absent', ['vpc_endpoint_id']], ] ) # Validate Requirements if not HAS_BOTO3: module.fail_json(msg='botocore and boto3 are required for this module') state = module.params.get('state') try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) except NameError as e: # Getting around the get_aws_connection_info boto reliance for region if "global name 'boto' is not defined" in e.message: module.params['region'] = botocore.session.get_session().get_config_variable('region') if not module.params['region']: module.fail_json(msg="Error - no region provided") else: module.fail_json(msg="Can't retrieve connection information - " + str(e), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) ec2 = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg="Failed to connect to AWS due to wrong or missing credentials: %s" % str(e), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) # Ensure resource is present if state == 'present': (changed, results) = setup_creation(ec2, module) else: (changed, results) = setup_removal(ec2, module) module.exit_json(changed=changed, result=results)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(filters=dict(type='dict', default=dict()), vpn_gateway_ids=dict(type='list', default=None))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'ec2_vpc_vgw_facts': module.deprecate( "The 'ec2_vpc_vgw_facts' module has been renamed to 'ec2_vpc_vgw_info'", version='2.13') # Validate Requirements if not HAS_BOTO3: module.fail_json(msg='json and boto3 is required.') try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info( module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg="Can't authorize connection - " + str(e)) # call your function here results = list_virtual_gateways(connection, module) module.exit_json(virtual_gateways=results)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(filters=dict(type='dict', default={}), dry_run=dict(type='bool', default=False, aliases=['DryRun']), dhcp_options_ids=dict(type='list', aliases=['DhcpOptionIds']))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'ec2_vpc_dhcp_option_facts': module.deprecate( "The 'ec2_vpc_dhcp_option_facts' module has been renamed to 'ec2_vpc_dhcp_option_info'", version='2.13') # Validate Requirements if not HAS_BOTO3: module.fail_json(msg='boto3 and botocore are required.') try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info( module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg="Can't authorize connection - " + str(e)) # call your function here results = list_dhcp_options(connection, module) module.exit_json(dhcp_options=results)
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( subnet_ids=dict(type='list', default=[], aliases=['subnet_id']), filters=dict(type='dict', default={}) )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'ec2_vpc_subnet_facts': module.deprecate("The 'ec2_vpc_subnet_facts' module has been renamed to 'ec2_vpc_subnet_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 is required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: try: connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params) except (botocore.exceptions.NoCredentialsError, botocore.exceptions.ProfileNotFound) as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) else: module.fail_json(msg="Region must be specified") describe_subnets(connection, module)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( instance_ids=dict(default=[], type='list'), filters=dict(default={}, type='dict') ) ) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[ ['instance_ids', 'filters'] ], supports_check_mode=True ) if module._name == 'ec2_instance_facts': module.deprecate("The 'ec2_instance_facts' module has been renamed to 'ec2_instance_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params) else: module.fail_json(msg="region must be specified") list_ec2_instances(connection, module)
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict(log_group_name=dict(), )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'cloudwatchlogs_log_group_facts': module.deprecate( "The 'cloudwatchlogs_log_group_facts' module has been renamed to 'cloudwatchlogs_log_group_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 is required.') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) logs = boto3_conn(module, conn_type='client', resource='logs', region=region, endpoint=ec2_url, **aws_connect_kwargs) desc_log_group = describe_log_group( client=logs, log_group_name=module.params['log_group_name'], module=module) final_log_group_snake = [] for log_group in desc_log_group['logGroups']: final_log_group_snake.append(camel_dict_to_snake_dict(log_group)) desc_log_group_result = dict(changed=False, log_groups=final_log_group_snake) module.exit_json(**desc_log_group_result)
def get_s3_connection(module, aws_connect_kwargs, location, rgw, s3_url, sig_4=False): if s3_url and rgw: # TODO - test this rgw = urlparse(s3_url) params = dict(module=module, conn_type='client', resource='s3', use_ssl=rgw.scheme == 'https', region=location, endpoint=s3_url, **aws_connect_kwargs) elif is_fakes3(s3_url): fakes3 = urlparse(s3_url) port = fakes3.port if fakes3.scheme == 'fakes3s': protocol = "https" if port is None: port = 443 else: protocol = "http" if port is None: port = 80 params = dict(module=module, conn_type='client', resource='s3', region=location, endpoint="%s://%s:%s" % (protocol, fakes3.hostname, to_text(port)), use_ssl=fakes3.scheme == 'fakes3s', **aws_connect_kwargs) else: params = dict(module=module, conn_type='client', resource='s3', region=location, endpoint=s3_url, **aws_connect_kwargs) if module.params['mode'] == 'put' and module.params['encryption_mode'] == 'aws:kms': params['config'] = botocore.client.Config(signature_version='s3v4') elif module.params['mode'] in ('get', 'getstr') and sig_4: params['config'] = botocore.client.Config(signature_version='s3v4') if module.params['dualstack']: dualconf = botocore.client.Config(s3={'use_dualstack_endpoint': True}) if 'config' in params: params['config'] = params['config'].merge(dualconf) else: params['config'] = dualconf return boto3_conn(**params)
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict(name=dict(type='str'), )) module = AnsibleModule(argument_spec=argument_spec, ) if module._name == 'iam_server_certificate_facts': module.deprecate( "The 'iam_server_certificate_facts' module has been renamed to 'iam_server_certificate_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info( module, boto3=True) iam = boto3_conn(module, conn_type='client', resource='iam', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.ClientError as e: module.fail_json(msg="Boto3 Client Error - " + str(e.msg)) cert_name = module.params.get('name') results = get_server_certs(iam, cert_name) module.exit_json(results=results)
def __init__(self, ansible_obj, resources, boto3=True): self.region, self.endpoint, aws_connect_kwargs = get_aws_connection_info(ansible_obj, boto3=boto3) self.resource_client = dict() if not resources: resources = ['batch'] resources.append('iam') for resource in resources: aws_connect_kwargs.update(dict(region=self.region, endpoint=self.endpoint, conn_type='client', resource=resource )) self.resource_client[resource] = boto3_conn(ansible_obj, **aws_connect_kwargs) # if region is not provided, then get default profile/session region if not self.region: self.region = self.resource_client['batch'].meta.region_name # set account ID try: self.account_id = self.resource_client['iam'].get_user()['User']['Arn'].split(':')[4] except (ClientError, ValueError, KeyError, IndexError): self.account_id = ''
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(filters=dict(type='dict'), pending_deletion=dict(type='bool', default=False))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'aws_kms_facts': module.deprecate( "The 'aws_kms_facts' module has been renamed to 'aws_kms_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 and botocore are required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: connection = boto3_conn(module, conn_type='client', resource='kms', region=region, endpoint=ec2_url, **aws_connect_params) else: module.fail_json(msg="region must be specified") all_keys = get_kms_info(connection, module) module.exit_json(keys=[ key for key in all_keys if key_matches_filters(key, module.params['filters']) ])
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( name=dict(type='str'), tags=dict(type='dict'), )) module = AnsibleModule(argument_spec=argument_spec) if module._name == 'ec2_asg_facts': module.deprecate( "The 'ec2_asg_facts' module has been renamed to 'ec2_asg_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') asg_name = module.params.get('name') asg_tags = module.params.get('tags') try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info( module, boto3=True) autoscaling = boto3_conn(module, conn_type='client', resource='autoscaling', region=region, endpoint=ec2_url, **aws_connect_kwargs) except ClientError as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) results = find_asgs(autoscaling, module, name=asg_name, tags=asg_tags) module.exit_json(results=results)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( load_balancer_arn=dict(type='str'), target_group_arns=dict(type='list'), names=dict(type='list'), collect_targets_health=dict(default=False, type='bool', required=False) ) ) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[['load_balancer_arn', 'target_group_arns', 'names']], supports_check_mode=True ) if module._name == 'elb_target_group_facts': module.deprecate("The 'elb_target_group_facts' module has been renamed to 'elb_target_group_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: connection = boto3_conn(module, conn_type='client', resource='elbv2', region=region, endpoint=ec2_url, **aws_connect_params) else: module.fail_json(msg="region must be specified") list_target_groups(connection, module)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(source_region=dict(required=True), source_snapshot_id=dict(required=True), description=dict(default=''), encrypted=dict(type='bool', default=False, required=False), kms_key_id=dict(type='str', required=False), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=600), tags=dict(type='dict'))) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO3: module.fail_json(msg='botocore and boto3 are required.') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) client = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) copy_snapshot(module, client)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(name=dict(required=True, type='str'), rules=dict(type='list'), state=dict(type='str', choices=['present', 'absent'], required=True))) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO3: module.fail_json(msg='boto3 is required.') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) client = boto3_conn(module, conn_type='client', resource='s3', region=region, endpoint=ec2_url, **aws_connect_kwargs) state = module.params.get("state") if state == 'present': create_or_update_bucket_cors(client, module) elif state == 'absent': destroy_bucket_cors(client, module)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(state=dict(default='present', choices=['present', 'absent']), name=dict(), amazon_asn=dict(), virtual_gateway_id=dict(), direct_connect_gateway_id=dict(), wait_timeout=dict(type='int', default=320))) required_if = [('state', 'present', ['name', 'amazon_asn']), ('state', 'absent', ['direct_connect_gateway_id'])] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if) if not HAS_BOTO3: module.fail_json(msg='boto3 is required for this module') state = module.params.get('state') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) client = boto3_conn(module, conn_type='client', resource='directconnect', region=region, endpoint=ec2_url, **aws_connect_kwargs) if state == 'present': (changed, results) = ensure_present(client, module) elif state == 'absent': changed = ensure_absent(client, module) results = {} module.exit_json(changed=changed, **camel_dict_to_snake_dict(results))
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( deregister_unused=dict(type='bool', default=False), target_az=dict(type='str'), target_group_arn=dict(type='str'), target_group_name=dict(type='str'), target_id=dict(type='str', required=True), target_port=dict(type='int'), target_status=dict(choices=['initial', 'healthy', 'unhealthy', 'unused', 'draining', 'unavailable'], type='str'), target_status_timeout=dict(type='int', default=60), state=dict(required=True, choices=['present', 'absent'], type='str'), ) ) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[['target_group_arn', 'target_group_name']] ) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='elbv2', region=region, endpoint=ec2_url, **aws_connect_params) state = module.params.get("state") if state == 'present': register_target(connection, module) else: deregister_target(connection, module)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(duration_seconds=dict(required=False, default=None, type='int'), mfa_serial_number=dict(required=False, default=None), mfa_token=dict(required=False, default=None))) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO3: module.fail_json(msg='boto3 and botocore are required.') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) if region: connection = boto3_conn(module, conn_type='client', resource='sts', region=region, endpoint=ec2_url, **aws_connect_kwargs) else: module.fail_json(msg="region must be specified") get_session_token(connection, module)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(vpc_ids=dict(type='list', default=[]), filters=dict(type='dict', default={}))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'ec2_vpc_net_facts': module.deprecate( "The 'ec2_vpc_net_facts' module has been renamed to 'ec2_vpc_net_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 and botocore are required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params) describe_vpcs(connection, module)
def get_account_info(module, region=None, endpoint=None, **aws_connect_kwargs): """return the account information (account id and partition) we are currently working on get_account_info tries too find out the account that we are working on. It's not guaranteed that this will be easy so we try in several different ways. Giving either IAM or STS privileges to the account should be enough to permit this. """ account_id = None partition = None try: sts_client = boto3_conn(module, conn_type='client', resource='sts', region=region, endpoint=endpoint, **aws_connect_kwargs) caller_id = sts_client.get_caller_identity() account_id = caller_id.get('Account') partition = caller_id.get('Arn').split(':')[1] except ClientError: try: iam_client = boto3_conn(module, conn_type='client', resource='iam', region=region, endpoint=endpoint, **aws_connect_kwargs) arn, partition, service, reg, account_id, resource = iam_client.get_user( )['User']['Arn'].split(':') except ClientError as e: if (e.response['Error']['Code'] == 'AccessDenied'): except_msg = to_native(e.message) m = except_msg.search( r"arn:(aws(-([a-z\-]+))?):iam::([0-9]{12,32}):\w+/") account_id = m.group(4) partition = m.group(1) if account_id is None: module.fail_json_aws(e, msg="getting account information") if partition is None: module.fail_json_aws( e, msg="getting account information: partition") except Exception as e: module.fail_json_aws(e, msg="getting account information") return account_id, partition
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(name=dict(type='str', required=True), state=dict(type='str', required=True, choices=['present', 'absent']), suffix=dict(type='str', required=False, default='index.html'), error_key=dict(type='str', required=False), redirect_all_requests=dict(type='str', required=False))) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[['redirect_all_requests', 'suffix'], ['redirect_all_requests', 'error_key']]) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: client_connection = boto3_conn(module, conn_type='client', resource='s3', region=region, endpoint=ec2_url, **aws_connect_params) resource_connection = boto3_conn(module, conn_type='resource', resource='s3', region=region, endpoint=ec2_url, **aws_connect_params) else: module.fail_json(msg="region must be specified") state = module.params.get("state") if state == 'present': enable_or_update_bucket_as_website(client_connection, resource_connection, module) elif state == 'absent': disable_bucket_as_website(client_connection, module)
def dependencies(): # each LAG dict will contain the keys: module, connections, virtual_interfaces Dependencies = collections.namedtuple("Dependencies", ["lag_1", "lag_2"]) lag_1 = dict() lag_2 = dict() vanilla_params = { "name": "ansible_lag_1", "location": "EqSe2", "num_connections": 1, "min_links": 0, "bandwidth": "1Gbps" } for lag in ("ansible_lag_1", "ansible_lag_2"): params = dict(vanilla_params) params["name"] = lag if lag == "ansible_lag_1": lag_1["module"] = FakeModule(**params) else: lag_2["module"] = FakeModule(**params) if os.getenv("PLACEBO_RECORD"): region, ec2_url, aws_connect_kwargs = get_aws_connection_info( lag_1["module"], boto3=True) client = boto3_conn(lag_1["module"], conn_type="client", resource="directconnect", region=region, endpoint=ec2_url, **aws_connect_kwargs) # See if link aggregation groups exist for name in ("ansible_lag_1", "ansible_lag_2"): lag_id = lag_module.create_lag(client, num_connections=1, location="EqSe2", bandwidth="1Gbps", name=name, connection_id=None) if name == "ansible_lag_1": lag_1["lag_id"] = lag_id lag_1["name"] = name else: lag_2["lag_id"] = lag_id lag_2["name"] = name yield Dependencies(lag_1=lag_1, lag_2=lag_2) else: lag_1.update(lag_id="dxlag-fgkk4dja", name="ansible_lag_1") lag_2.update(lag_id="dxlag-fgytkicv", name="ansible_lag_2") yield Dependencies(lag_1=lag_1, lag_2=lag_2) if os.getenv("PLACEBO_RECORD"): # clean up lag_module.ensure_absent(client, lag_1["lag_id"], lag_1["name"], True, True, True, 120) lag_module.ensure_absent(client, lag_2["lag_id"], lag_2["name"], True, True, True, 120)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict(name=dict(required=True), image_id=dict(), instance_id=dict(), key_name=dict(), security_groups=dict(default=[], type='list'), user_data=dict(), user_data_path=dict(type='path'), kernel_id=dict(), volumes=dict(type='list'), instance_type=dict(), state=dict(default='present', choices=['present', 'absent']), spot_price=dict(type='float'), ramdisk_id=dict(), instance_profile_name=dict(), ebs_optimized=dict(default=False, type='bool'), associate_public_ip_address=dict(type='bool', removed_in_version='2.14'), instance_monitoring=dict(default=False, type='bool'), assign_public_ip=dict(type='bool'), classic_link_vpc_security_groups=dict(type='list'), classic_link_vpc_id=dict(), vpc_id=dict(), placement_tenancy=dict(choices=['default', 'dedicated']))) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[['user_data', 'user_data_path']]) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info( module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='autoscaling', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoRegionError: module.fail_json(msg=( "region must be specified as a parameter in AWS_DEFAULT_REGION environment variable or in boto configuration file" )) except botocore.exceptions.ClientError as e: module.fail_json(msg="unable to establish connection - " + str(e), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) state = module.params.get('state') if state == 'present': create_launch_config(connection, module) elif state == 'absent': delete_launch_config(connection, module)
def resource(self, service): region, ec2_url, aws_connect_kwargs = get_aws_connection_info( self, boto3=True) return boto3_conn(self, conn_type='resource', resource=service, region=region, endpoint=ec2_url, **aws_connect_kwargs)
def __init__(self, module): self.module = module try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) if not region: module.fail_json(msg="Region must be specified as a parameter, in EC2_REGION or AWS_REGION environment variables or in boto configuration file") self.ec2 = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) except ClientError as e: module.fail_json(msg=e.message)
def __init__(self, module): region, ec2_url, aws_connect_kwargs = \ get_aws_connection_info(module, boto3=True) self.ecr = boto3_conn(module, conn_type='client', resource='ecr', region=region, endpoint=ec2_url, **aws_connect_kwargs) self.sts = boto3_conn(module, conn_type='client', resource='sts', region=region, endpoint=ec2_url, **aws_connect_kwargs) self.check_mode = module.check_mode self.changed = False self.skipped = False
def __init__(self, module, region, **aws_connect_params): self.connection = boto3_conn(module, conn_type='client', resource='efs', region=region, **aws_connect_params) self.module = module self.region = region self.wait = module.params.get('wait') self.wait_timeout = module.params.get('wait_timeout')
def client(self, service, retry_decorator=None): region, ec2_url, aws_connect_kwargs = get_aws_connection_info( self, boto3=True) conn = boto3_conn(self, conn_type='client', resource=service, region=region, endpoint=ec2_url, **aws_connect_kwargs) return conn if retry_decorator is None else _RetryingBotoClientWrapper( conn, retry_decorator)
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict(filters=dict(default={}, type='dict'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'ec2_group_facts': module.deprecate( "The 'ec2_group_facts' module has been renamed to 'ec2_group_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params) else: module.fail_json(msg="region must be specified") # Replace filter key underscores with dashes, for compatibility, except if we're dealing with tags sanitized_filters = module.params.get("filters") for key in list(sanitized_filters): if not key.startswith("tag:"): sanitized_filters[key.replace("_", "-")] = sanitized_filters.pop(key) try: security_groups = connection.describe_security_groups( Filters=ansible_dict_to_boto3_filter_list(sanitized_filters)) except ClientError as e: module.fail_json(msg=e.message, exception=traceback.format_exc()) snaked_security_groups = [] for security_group in security_groups['SecurityGroups']: # Modify boto3 tags list to be ansible friendly dict # but don't camel case tags security_group = camel_dict_to_snake_dict(security_group) security_group['tags'] = boto3_tag_list_to_ansible_dict( security_group.get('tags', {}), tag_name_key_name='key', tag_value_key_name='value') snaked_security_groups.append(security_group) module.exit_json(security_groups=snaked_security_groups)
def _get_elasticache_connection(self): """Get an elasticache connection""" region, ec2_url, aws_connect_params = get_aws_connection_info( self.module, boto3=True) if region: return boto3_conn(self.module, conn_type='client', resource='elasticache', region=region, endpoint=ec2_url, **aws_connect_params) else: self.module.fail_json(msg="region must be specified")
def __init__(self, module): self.module = module try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) self.client = boto3_conn(module, conn_type='client', resource='cloudfront', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoRegionError: self.module.fail_json(msg="Region must be specified as a parameter, in AWS_DEFAULT_REGION " "environment variable or in boto configuration file") except botocore.exceptions.ClientError as e: self.module.fail_json(msg="Can't establish connection - " + str(e), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))