def main():
    argument_spec = dict(
        db_snapshot_identifier=dict(aliases=['snapshot_name']),
        db_instance_identifier=dict(),
        db_cluster_identifier=dict(),
        db_cluster_snapshot_identifier=dict(),
        snapshot_type=dict(choices=['automated', 'manual', 'shared', 'public'])
    )

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        mutually_exclusive=[['db_snapshot_identifier', 'db_instance_identifier', 'db_cluster_identifier', 'db_cluster_snapshot_identifier']]
    )
    if module._name == 'rds_snapshot_facts':
        module.deprecate("The 'rds_snapshot_facts' module has been renamed to 'rds_snapshot_info'", version='2.13')

    conn = module.client('rds', retry_decorator=AWSRetry.jittered_backoff(retries=10))
    results = dict()
    if not module.params['db_cluster_identifier'] and not module.params['db_cluster_snapshot_identifier']:
        results['snapshots'] = standalone_snapshot_info(module, conn)
    if not module.params['db_snapshot_identifier'] and not module.params['db_instance_identifier']:
        results['cluster_snapshots'] = cluster_snapshot_info(module, conn)

    module.exit_json(changed=False, **results)
Example #2
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(task_definition=dict(required=True, type='str')))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    if module._name == 'ecs_taskdefinition_facts':
        module.deprecate(
            "The 'ecs_taskdefinition_facts' module has been renamed to 'ecs_taskdefinition_info'",
            version='2.13')

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module,
                                                                  boto3=True)
    ecs = boto3_conn(module,
                     conn_type='client',
                     resource='ecs',
                     region=region,
                     endpoint=ec2_url,
                     **aws_connect_kwargs)

    try:
        ecs_td = ecs.describe_task_definition(
            taskDefinition=module.params['task_definition'])['taskDefinition']
    except botocore.exceptions.ClientError:
        ecs_td = {}

    module.exit_json(changed=False, **camel_dict_to_snake_dict(ecs_td))
Example #3
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(names={'default': [], 'type': 'list'}))
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    if module._name == 'elb_classic_lb_facts':
        module.deprecate(
            "The 'elb_classic_lb_facts' module has been renamed to 'elb_classic_lb_info'",
            version='2.13')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module,
                                                                  boto3=True)
    connection = boto3_conn(module,
                            conn_type='client',
                            resource='elb',
                            region=region,
                            endpoint=ec2_url,
                            **aws_connect_params)

    try:
        elbs = list_elbs(connection, module.params.get('names'))
    except (botocore.exceptions.ClientError,
            botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to get load balancer information.")

    module.exit_json(elbs=elbs)
Example #4
0
def main():
    """
     Module action handler
    """
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            name=dict(aliases=['role_name']),
            path_prefix=dict(),
        ))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True,
                              mutually_exclusive=[['name', 'path_prefix']])
    if module._name == 'iam_role_facts':
        module.deprecate(
            "The 'iam_role_facts' module has been renamed to 'iam_role_info'",
            version='2.13')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module,
                                                                  boto3=True)
    client = boto3_conn(module,
                        conn_type='client',
                        resource='iam',
                        region=region,
                        endpoint=ec2_url,
                        **aws_connect_params)

    module.exit_json(changed=False,
                     iam_roles=describe_iam_roles(module, client))
def main():
    module = AnsibleAWSModule(
        argument_spec={},
        supports_check_mode=True,
    )
    if module._name == 'aws_caller_facts':
        module.deprecate(
            "The 'aws_caller_facts' module has been renamed to 'aws_caller_info'",
            version='2.13')

    client = module.client('sts')

    try:
        caller_info = client.get_caller_identity()
        caller_info.pop('ResponseMetadata', None)
    except (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e, msg='Failed to retrieve caller identity')

    iam_client = module.client('iam')

    try:
        # Although a list is returned by list_account_aliases AWS supports maximum one alias per account.
        # If an alias is defined it will be returned otherwise a blank string is filled in as account_alias.
        # see https://docs.aws.amazon.com/cli/latest/reference/iam/list-account-aliases.html#output
        response = iam_client.list_account_aliases()
        if response and response['AccountAliases']:
            caller_info['account_alias'] = response['AccountAliases'][0]
        else:
            caller_info['account_alias'] = ''
    except (BotoCoreError, ClientError) as e:
        # The iam:ListAccountAliases permission is required for this operation to succeed.
        # Lacking this permission is handled gracefully by not returning the account_alias.
        pass

    module.exit_json(changed=False, **camel_dict_to_snake_dict(caller_info))
def main():
    argument_spec = dict(instance_id={
        "required": True,
        "type": "str"
    },
                         get_unused_target_groups={
                             "required": False,
                             "default": True,
                             "type": "bool"
                         })

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    if module._name == 'elb_target_facts':
        module.deprecate(
            "The 'elb_target_facts' module has been renamed to 'elb_target_info'",
            version='2.13')

    instance_id = module.params["instance_id"]
    get_unused_target_groups = module.params["get_unused_target_groups"]

    tg_gatherer = TargetInfoGatherer(module, instance_id,
                                     get_unused_target_groups)

    instance_target_groups = [each.to_dict() for each in tg_gatherer.tgs]

    module.exit_json(instance_target_groups=instance_target_groups)
def main():
    argument_spec = dict(
        iam_type=dict(required=True, choices=['user', 'group', 'role']),
        state=dict(default='present', choices=['present', 'absent']),
        iam_name=dict(required=True),
        policy_name=dict(required=True),
        policy_document=dict(default=None, required=False),
        policy_json=dict(type='json', default=None, required=False),
        skip_duplicates=dict(type='bool', default=None, required=False)
    )
    mutually_exclusive = [['policy_document', 'policy_json']]

    module = AnsibleAWSModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True)

    skip_duplicates = module.params.get('skip_duplicates')

    if (skip_duplicates is None):
        module.deprecate('The skip_duplicates behaviour has caused confusion and'
                         ' will be disabled by default in Ansible 2.14',
                         version='2.14')
        skip_duplicates = True

    if module.params.get('policy_document'):
        module.deprecate('The policy_document option has been deprecated and'
                         ' will be removed in Ansible 2.14',
                         version='2.14')

    args = dict(
        client=module.client('iam'),
        name=module.params.get('iam_name'),
        policy_name=module.params.get('policy_name'),
        policy_document=module.params.get('policy_document'),
        policy_json=module.params.get('policy_json'),
        skip_duplicates=skip_duplicates,
        state=module.params.get('state'),
        check_mode=module.check_mode,
    )
    iam_type = module.params.get('iam_type')

    try:
        if iam_type == 'user':
            policy = UserPolicy(**args)
        elif iam_type == 'role':
            policy = RolePolicy(**args)
        elif iam_type == 'group':
            policy = GroupPolicy(**args)

        module.exit_json(**(policy.run()))
    except (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e)
    except PolicyError as e:
        module.fail_json(msg=str(e))
def main():
    """
    Module action handler
    """
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(id=dict(),
             name=dict(aliases=['creation_token']),
             tags=dict(type="dict", default={}),
             targets=dict(type="list", default=[])))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    is_old_facts = module._name == 'efs_facts'
    if is_old_facts:
        module.deprecate(
            "The 'efs_facts' module has been renamed to 'efs_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module,
                                                                  boto3=True)
    connection = EFSConnection(module, region, **aws_connect_params)

    name = module.params.get('name')
    fs_id = module.params.get('id')
    tags = module.params.get('tags')
    targets = module.params.get('targets')

    file_systems_info = connection.get_file_systems(fs_id, name)

    if tags:
        file_systems_info = [
            item for item in file_systems_info if has_tags(item['tags'], tags)
        ]

    file_systems_info = connection.get_mount_targets_data(file_systems_info)
    file_systems_info = connection.get_security_groups_data(file_systems_info)

    if targets:
        targets = [(item, prefix_to_attr(item)) for item in targets]
        file_systems_info = [
            item for item in file_systems_info
            if has_targets(item['mount_targets'], targets)
        ]

    if is_old_facts:
        module.exit_json(changed=False,
                         ansible_facts={'efs': file_systems_info})
    else:
        module.exit_json(changed=False, efs=file_systems_info)
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=False),
        )
    )
    module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
    if module._name == 'elasticache_facts':
        module.deprecate("The 'elasticache_facts' module has been renamed to 'elasticache_info'", version='2.13')

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
    client = boto3_conn(module, conn_type='client', resource='elasticache',
                        region=region, endpoint=ec2_url, **aws_connect_kwargs)

    module.exit_json(elasticache_clusters=get_elasticache_clusters(client, module, region))
Example #10
0
def main():

    argument_spec = dict(nacl_ids=dict(default=[],
                                       type='list',
                                       aliases=['nacl_id']),
                         filters=dict(default={}, type='dict'))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    if module._name == 'ec2_vpc_nacl_facts':
        module.deprecate(
            "The 'ec2_vpc_nacl_facts' module has been renamed to 'ec2_vpc_nacl_info'",
            version='2.13')

    connection = module.client('ec2')

    list_ec2_vpc_nacls(connection, module)
Example #11
0
def main():
    argument_spec = dict(db_instance_identifier=dict(aliases=['id']),
                         filters=dict(type='dict'))

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    if module._name == 'rds_instance_facts':
        module.deprecate(
            "The 'rds_instance_facts' module has been renamed to 'rds_instance_info'",
            version='2.13')

    conn = module.client('rds',
                         retry_decorator=AWSRetry.jittered_backoff(retries=10))

    module.exit_json(**instance_info(module, conn))
Example #12
0
def main():
    argument_spec = dict(gather_local_disks=dict(type='bool', default=True),
                         gather_tapes=dict(type='bool', default=True),
                         gather_file_shares=dict(type='bool', default=True),
                         gather_volumes=dict(type='bool', default=True))

    module = AnsibleAWSModule(argument_spec=argument_spec)
    if module._name == 'aws_sgw_facts':
        module.deprecate(
            "The 'aws_sgw_facts' module has been renamed to 'aws_sgw_info'",
            version='2.13')
    client = module.client('storagegateway')

    if client is None:  # this should never happen
        module.fail_json(
            msg=
            'Unknown error, failed to create storagegateway client, no information from boto.'
        )

    SGWInformationManager(client, module).fetch()
def main():

    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(details=dict(type='bool', default=False),
             events=dict(type='bool', default=True),
             cluster=dict(),
             service=dict(type='list')))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    is_old_facts = module._name == 'ecs_service_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ecs_service_facts' module has been renamed to 'ecs_service_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    show_details = module.params.get('details')

    task_mgr = EcsServiceManager(module)
    if show_details:
        if module.params['service']:
            services = module.params['service']
        else:
            services = task_mgr.list_services(
                module.params['cluster'])['services']
        ecs_info = dict(services=[], services_not_running=[])
        for chunk in chunks(services, 10):
            running_services, services_not_running = task_mgr.describe_services(
                module.params['cluster'], chunk)
            ecs_info['services'].extend(running_services)
            ecs_info['services_not_running'].extend(services_not_running)
    else:
        ecs_info = task_mgr.list_services(module.params['cluster'])

    if is_old_facts:
        module.exit_json(changed=False, ansible_facts=ecs_info, **ecs_info)
    else:
        module.exit_json(changed=False, **ecs_info)
def main():
    argument_spec = dict(name=dict(required=False),
                         waf_regional=dict(type='bool', default=False))
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    if module._name == 'aws_waf_facts':
        module.deprecate(
            "The 'aws_waf_facts' module has been renamed to 'aws_waf_info'",
            version='2.13')

    resource = 'waf' if not module.params['waf_regional'] else 'waf-regional'
    client = module.client(resource)
    web_acls = list_web_acls(client, module)
    name = module.params['name']
    if name:
        web_acls = [web_acl for web_acl in web_acls if web_acl['Name'] == name]
        if not web_acls:
            module.fail_json(msg="WAF named %s not found" % name)
    module.exit_json(wafs=[
        get_web_acl(client, module, web_acl['WebACLId'])
        for web_acl in web_acls
    ])
def main():
    argument_spec = dict(
        certificate_arn=dict(aliases=['arn']),
        domain_name=dict(aliases=['name']),
        statuses=dict(type='list',
                      choices=[
                          'PENDING_VALIDATION', 'ISSUED', 'INACTIVE',
                          'EXPIRED', 'VALIDATION_TIMED_OUT', 'REVOKED',
                          'FAILED'
                      ]),
        tags=dict(type='dict'),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    acm_info = ACMServiceManager(module)

    if module._name == 'aws_acm_facts':
        module.deprecate(
            "The 'aws_acm_facts' module has been renamed to 'aws_acm_info'",
            version='2.13')

    client = module.client('acm')

    certificates = acm_info.get_certificates(
        client,
        module,
        domain_name=module.params['domain_name'],
        statuses=module.params['statuses'],
        arn=module.params['certificate_arn'],
        only_tags=module.params['tags'])

    if module.params['certificate_arn'] and len(certificates) != 1:
        module.fail_json(
            msg="No certificate exists in this region with ARN %s" %
            module.params['certificate_arn'])

    module.exit_json(certificates=certificates)
def main():
    argument_spec = dict(
        stack_name=dict(),
        all_facts=dict(required=False, default=False, type='bool'),
        stack_policy=dict(required=False, default=False, type='bool'),
        stack_events=dict(required=False, default=False, type='bool'),
        stack_resources=dict(required=False, default=False, type='bool'),
        stack_template=dict(required=False, default=False, type='bool'),
        stack_change_sets=dict(required=False, default=False, type='bool'),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)

    is_old_facts = module._name == 'cloudformation_facts'
    if is_old_facts:
        module.deprecate(
            "The 'cloudformation_facts' module has been renamed to 'cloudformation_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    service_mgr = CloudFormationServiceManager(module)

    if is_old_facts:
        result = {'ansible_facts': {'cloudformation': {}}}
    else:
        result = {'cloudformation': {}}

    for stack_description in service_mgr.describe_stacks(
            module.params.get('stack_name')):
        facts = {'stack_description': stack_description}
        stack_name = stack_description.get('StackName')

        # Create stack output and stack parameter dictionaries
        if facts['stack_description']:
            facts['stack_outputs'] = to_dict(
                facts['stack_description'].get('Outputs'), 'OutputKey',
                'OutputValue')
            facts['stack_parameters'] = to_dict(
                facts['stack_description'].get('Parameters'), 'ParameterKey',
                'ParameterValue')
            facts['stack_tags'] = boto3_tag_list_to_ansible_dict(
                facts['stack_description'].get('Tags'))

        # Create optional stack outputs
        all_facts = module.params.get('all_facts')
        if all_facts or module.params.get('stack_resources'):
            facts['stack_resource_list'] = service_mgr.list_stack_resources(
                stack_name)
            facts['stack_resources'] = to_dict(
                facts.get('stack_resource_list'), 'LogicalResourceId',
                'PhysicalResourceId')
        if all_facts or module.params.get('stack_template'):
            facts['stack_template'] = service_mgr.get_template(stack_name)
        if all_facts or module.params.get('stack_policy'):
            facts['stack_policy'] = service_mgr.get_stack_policy(stack_name)
        if all_facts or module.params.get('stack_events'):
            facts['stack_events'] = service_mgr.describe_stack_events(
                stack_name)
        if all_facts or module.params.get('stack_change_sets'):
            facts[
                'stack_change_sets'] = service_mgr.describe_stack_change_sets(
                    stack_name)

        if is_old_facts:
            result['ansible_facts']['cloudformation'][stack_name] = facts
        else:
            result['cloudformation'][stack_name] = camel_dict_to_snake_dict(
                facts,
                ignore_list=('stack_outputs', 'stack_parameters',
                             'stack_policy', 'stack_resources', 'stack_tags',
                             'stack_template'))

    module.exit_json(changed=False, **result)
Example #17
0
def main():

    argument_spec = (dict(
        cross_zone_load_balancing=dict(type='bool'),
        deletion_protection=dict(type='bool'),
        listeners=dict(type='list',
                       elements='dict',
                       options=dict(Protocol=dict(type='str', required=True),
                                    Port=dict(type='int', required=True),
                                    SslPolicy=dict(type='str'),
                                    Certificates=dict(type='list'),
                                    DefaultActions=dict(type='list',
                                                        required=True))),
        name=dict(required=True, type='str'),
        purge_listeners=dict(default=True, type='bool'),
        purge_tags=dict(default=True, type='bool'),
        subnets=dict(type='list'),
        subnet_mappings=dict(type='list'),
        scheme=dict(default='internet-facing',
                    choices=['internet-facing', 'internal']),
        state=dict(choices=['present', 'absent'], type='str'),
        tags=dict(type='dict'),
        wait_timeout=dict(type='int'),
        wait=dict(type='bool')))

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        mutually_exclusive=[['subnets', 'subnet_mappings']])

    # Check for subnets or subnet_mappings if state is present
    state = module.params.get("state")
    if state == 'present':
        if module.params.get("subnets") is None and module.params.get(
                "subnet_mappings") is None:
            module.fail_json(
                msg=
                "'subnets' or 'subnet_mappings' is required when state=present"
            )

    if state is None:
        # See below, unless state==present we delete.  Ouch.
        module.deprecate(
            'State currently defaults to absent.  This is inconsistent with other modules'
            ' and the default will be changed to `present` in Ansible 2.14',
            version='2.14')

    # Quick check of listeners parameters
    listeners = module.params.get("listeners")
    if listeners is not None:
        for listener in listeners:
            for key in listener.keys():
                protocols_list = ['TCP', 'TLS', 'UDP', 'TCP_UDP']
                if key == 'Protocol' and listener[key] not in protocols_list:
                    module.fail_json(msg="'Protocol' must be either " +
                                     ", ".join(protocols_list))

    connection = module.client('elbv2')
    connection_ec2 = module.client('ec2')

    elb = NetworkLoadBalancer(connection, connection_ec2, module)

    if state == 'present':
        create_or_update_elb(elb)
    else:
        delete_elb(elb)
def main():
    argument_spec = dict(
        alias=dict(aliases=['key_alias']),
        policy_mode=dict(aliases=['mode'],
                         choices=['grant', 'deny'],
                         default='grant'),
        policy_role_name=dict(aliases=['role_name']),
        policy_role_arn=dict(aliases=['role_arn']),
        policy_grant_types=dict(aliases=['grant_types'], type='list'),
        policy_clean_invalid_entries=dict(aliases=['clean_invalid_entries'],
                                          type='bool',
                                          default=True),
        key_id=dict(aliases=['key_arn']),
        description=dict(),
        enabled=dict(type='bool', default=True),
        tags=dict(type='dict', default={}),
        purge_tags=dict(type='bool', default=False),
        grants=dict(type='list', default=[]),
        policy=dict(),
        purge_grants=dict(type='bool', default=False),
        state=dict(default='present', choices=['present', 'absent']),
    )

    module = AnsibleAWSModule(
        supports_check_mode=True,
        argument_spec=argument_spec,
        required_one_of=[['alias', 'key_id']],
    )

    result = {}
    mode = module.params['policy_mode']

    kms = module.client('kms')
    iam = module.client('iam')

    key_id = module.params.get('key_id')
    alias = module.params.get('alias')
    if alias and alias.startswith('alias/'):
        alias = alias[6:]

    # Fetch/Canonicalize key_id where possible
    if key_id:
        try:
            # Don't use get_key_details it triggers module.fail when the key
            # doesn't exist
            key_metadata = get_kms_metadata_with_backoff(kms,
                                                         key_id)['KeyMetadata']
            key_id = key_metadata['Arn']
        except (botocore.exceptions.ClientError,
                botocore.exceptions.BotoCoreError) as e:
            # We can't create keys with a specific ID, if we can't access the
            # key we'll have to fail
            if module.params.get('state') == 'present':
                module.fail_json(msg="Could not find key with id %s to update")
            key_metadata = None
    elif alias:
        try:
            key_metadata = get_kms_metadata_with_backoff(
                kms, 'alias/%s' % alias)['KeyMetadata']
            key_id = key_metadata['Arn']
        except (botocore.exceptions.ClientError,
                botocore.exceptions.BotoCoreError) as e:
            key_metadata = None

    if module.params.get('policy_grant_types') or mode == 'deny':
        module.deprecate(
            'Managing the KMS IAM Policy via policy_mode and policy_grant_types is fragile'
            ' and has been deprecated in favour of the policy option.',
            version='2.13')
        if module.params.get('policy_role_name'
                             ) and not module.params.get('policy_role_arn'):
            module.params['policy_role_arn'] = get_arn_from_role_name(
                iam, module.params['policy_role_name'])
        if not module.params.get('policy_role_arn'):
            module.fail_json(
                msg='policy_role_arn or policy_role_name is required to {0}'.
                format(module.params['policy_mode']))

        # check the grant types for 'grant' only.
        if mode == 'grant':
            for g in module.params['policy_grant_types']:
                if g not in statement_label:
                    module.fail_json(
                        msg='{0} is an unknown grant type.'.format(g))

        ret = do_policy_grant(module,
                              kms,
                              key_id,
                              module.params['policy_role_arn'],
                              module.params['policy_grant_types'],
                              mode=mode,
                              dry_run=module.check_mode,
                              clean_invalid_entries=module.
                              params['policy_clean_invalid_entries'])
        result.update(ret)

        module.exit_json(**result)

    else:
        if module.params.get('state') == 'present':
            if key_metadata:
                key_details = get_key_details(kms, module, key_id)
                update_key(kms, module, key_details)
            else:
                if key_id:
                    module.fail_json(
                        msg="Could not find key with id %s to update" % key_id)
                else:
                    create_key(kms, module)
        else:
            if key_metadata:
                delete_key(kms, module, key_metadata, key_id)
            else:
                module.exit_json(changed=False)