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))
Beispiel #2
0
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)
Beispiel #4
0
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)
Beispiel #5
0
def main():
    argument_spec = dict(
        resource=dict(required=True),
        tags=dict(type='dict'),
        purge_tags=dict(type='bool', default=False),
        state=dict(default='present', choices=['present', 'absent', 'list']),
    )
    required_if = [('state', 'present', ['tags']), ('state', 'absent', ['tags'])]

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

    resource = module.params['resource']
    tags = module.params['tags']
    state = module.params['state']
    purge_tags = module.params['purge_tags']

    result = {'changed': False}

    ec2 = module.client('ec2')

    current_tags = get_tags(ec2, module, resource)

    if state == 'list':
        module.deprecate(
            'Using the "list" state has been deprecated.  Please use the ec2_tag_info module instead', version='2.14')
        module.exit_json(changed=False, tags=current_tags)

    add_tags, remove = compare_aws_tags(current_tags, tags, purge_tags=purge_tags)

    remove_tags = {}
    if state == 'absent':
        for key in tags:
            if key in current_tags and (tags[key] is None or current_tags[key] == tags[key]):
                remove_tags[key] = current_tags[key]

    for key in remove:
        remove_tags[key] = current_tags[key]

    if remove_tags:
        result['changed'] = True
        result['removed_tags'] = remove_tags
        if not module.check_mode:
            try:
                ec2.delete_tags(Resources=[resource], Tags=ansible_dict_to_boto3_tag_list(remove_tags))
            except (BotoCoreError, ClientError) as e:
                module.fail_json_aws(e, msg='Failed to remove tags {0} from resource {1}'.format(remove_tags, resource))

    if state == 'present' and add_tags:
        result['changed'] = True
        result['added_tags'] = add_tags
        current_tags.update(add_tags)
        if not module.check_mode:
            try:
                ec2.create_tags(Resources=[resource], Tags=ansible_dict_to_boto3_tag_list(add_tags))
            except (BotoCoreError, ClientError) as e:
                module.fail_json_aws(e, msg='Failed to set tags {0} on resource {1}'.format(add_tags, resource))

    result['tags'] = get_tags(ec2, module, resource)
    module.exit_json(**result)
Beispiel #6
0
def main():
    argument_spec = 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')

    client = module.client('elasticache')

    module.exit_json(elasticache_clusters=get_elasticache_clusters(client, module))
Beispiel #7
0
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']),
        enable_key_rotation=(dict(type='bool'))
    )

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

    mode = module.params['policy_mode']

    kms = module.client('kms')

    key_metadata = fetch_key_metadata(kms, module, module.params.get('key_id'), module.params.get('alias'))
    # 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' and module.params.get('key_id') and not key_metadata:
        module.fail_json(msg="Could not find key with id %s to update")

    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')
        result = update_policy_grants(kms, module, key_metadata, mode)
        module.exit_json(**result)

    if module.params.get('state') == 'absent':
        if key_metadata is None:
            module.exit_json(changed=False)
        result = delete_key(kms, module, key_metadata)
        module.exit_json(**result)

    if key_metadata:
        key_details = get_key_details(kms, module, key_metadata['Arn'])
        result = update_key(kms, module, key_details)
        module.exit_json(**result)

    result = create_key(kms, module)
    module.exit_json(**result)
Beispiel #8
0
def main():

    argument_spec = dict(
        name=dict(type='str', required=True),
        path=dict(type='str', default="/"),
        assume_role_policy_document=dict(type='json'),
        managed_policies=dict(type='list', aliases=['managed_policy']),
        max_session_duration=dict(type='int'),
        state=dict(type='str', choices=['present', 'absent'], default='present'),
        description=dict(type='str'),
        boundary=dict(type='str', aliases=['boundary_policy_arn']),
        create_instance_profile=dict(type='bool', default=True),
        delete_instance_profile=dict(type='bool', default=False),
        purge_policies=dict(type='bool', aliases=['purge_policy', 'purge_managed_policies']),
        tags=dict(type='dict'),
        purge_tags=dict(type='bool', default=True),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[('state', 'present', ['assume_role_policy_document'])],
                              supports_check_mode=True)

    if module.params.get('purge_policies') is None:
        module.deprecate('In Ansible 2.14 the default value of purge_policies will change from true to false.'
                         '  To maintain the existing behaviour explicity set purge_policies=true', version='2.14')

    if module.params.get('boundary'):
        if module.params.get('create_instance_profile'):
            module.fail_json(msg="When using a boundary policy, `create_instance_profile` must be set to `false`.")
        if not module.params.get('boundary').startswith('arn:aws:iam'):
            module.fail_json(msg="Boundary policy must be an ARN")
    if module.params.get('tags') is not None and not module.botocore_at_least('1.12.46'):
        module.fail_json(msg="When managing tags botocore must be at least v1.12.46. "
                         "Current versions: boto3-{boto3_version} botocore-{botocore_version}".format(**module._gather_versions()))
    if module.params.get('boundary') is not None and not module.botocore_at_least('1.10.57'):
        module.fail_json(msg="When using a boundary policy, botocore must be at least v1.10.57. "
                         "Current versions: boto3-{boto3_version} botocore-{botocore_version}".format(**module._gather_versions()))
    if module.params.get('max_session_duration'):
        max_session_duration = module.params.get('max_session_duration')
        if max_session_duration < 3600 or max_session_duration > 43200:
            module.fail_json(msg="max_session_duration must be between 1 and 12 hours (3600 and 43200 seconds)")
    if module.params.get('path'):
        path = module.params.get('path')
        if not path.endswith('/') or not path.startswith('/'):
            module.fail_json(msg="path must begin and end with /")

    connection = module.client('iam', retry_decorator=AWSRetry.jittered_backoff())

    state = module.params.get("state")

    if state == 'present':
        create_or_update_role(connection, module)
    else:
        destroy_role(connection, module)
Beispiel #9
0
def main():
    argument_spec = dict(
        iam_type=dict(required=True, choices=['user', 'group', 'role']),
        state=dict(default='present', choices=['present', 'absent']),
        iam_name=dict(default=None, required=False),
        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))
Beispiel #10
0
def main():
    argument_spec = dict(filters=dict(default={}, type='dict'))

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

    connection = module.client('ec2')

    list_ec2_volumes(connection, module)
Beispiel #11
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', retry_decorator=AWSRetry.jittered_backoff())

    list_ec2_vpc_nacls(connection, module)
Beispiel #12
0
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))
Beispiel #14
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()
Beispiel #15
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))
Beispiel #16
0
def main():
    argument_spec = 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')

    connection = module.client('elb')

    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)
Beispiel #17
0
def main():
    """
     Module action handler
    """
    argument_spec = 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')

    client = module.client('iam')

    module.exit_json(changed=False, iam_roles=describe_iam_roles(module, client))
Beispiel #18
0
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')

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

    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)
Beispiel #19
0
def main():

    argument_spec = dict(
        name=dict(type='str'),
        tags=dict(type='dict'),
    )
    module = AnsibleAWSModule(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')

    asg_name = module.params.get('name')
    asg_tags = module.params.get('tags')

    autoscaling = module.client('autoscaling')

    results = find_asgs(autoscaling, module, name=asg_name, tags=asg_tags)
    module.exit_json(results=results)
Beispiel #20
0
def main():
    argument_spec = 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')

    ecs = module.client('ecs')

    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))
Beispiel #21
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)
Beispiel #22
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))
Beispiel #23
0
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)
Beispiel #24
0
def main():

    argument_spec = dict(cluster_identifier=dict(
        type='str', aliases=['identifier', 'name']),
                         tags=dict(type='dict'))
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    if module._name == 'redshift_facts':
        module.deprecate(
            "The 'redshift_facts' module has been renamed to 'redshift_info'",
            version='2.13')

    cluster_identifier = module.params.get('cluster_identifier')
    cluster_tags = module.params.get('tags')

    redshift = module.client('redshift')

    results = find_clusters(redshift,
                            module,
                            identifier=cluster_identifier,
                            tags=cluster_tags)
    module.exit_json(results=results)
Beispiel #25
0
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
    ])
Beispiel #26
0
def main():
    argument_spec = dict(filters=dict(default={}, type='dict'))

    module = AnsibleAWSModule(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')

    connection = module.client('ec2')

    # 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 (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e, msg='Failed to describe security groups')

    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 main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        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')

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
    resource = 'waf' if not module.params['waf_regional'] else 'waf-regional'
    client = boto3_conn(module, conn_type='client', resource=resource, region=region, endpoint=ec2_url, **aws_connect_kwargs)
    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])
Beispiel #28
0
def main():
    argument_spec = dict(filters=dict(default={}, type='dict'))

    module = AnsibleAWSModule(argument_spec=argument_spec)
    if module._name == 'aws_region_facts':
        module.deprecate(
            "The 'aws_region_facts' module has been renamed to 'aws_region_info'",
            version='2.13')

    connection = module.client('ec2',
                               retry_decorator=AWSRetry.jittered_backoff())

    # Replace filter key underscores with dashes, for compatibility
    sanitized_filters = dict((k.replace('_', '-'), v)
                             for k, v in module.params.get('filters').items())

    try:
        regions = connection.describe_regions(
            Filters=ansible_dict_to_boto3_filter_list(sanitized_filters))
    except (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e, msg="Unable to describe regions.")

    module.exit_json(
        regions=[camel_dict_to_snake_dict(r) for r in regions['Regions']])
Beispiel #29
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(bucket=dict(required=True),
             dest=dict(default=None, type='path'),
             encrypt=dict(default=True, type='bool'),
             encryption_mode=dict(choices=['AES256', 'aws:kms'],
                                  default='AES256'),
             expiry=dict(default=600, type='int', aliases=['expiration']),
             headers=dict(type='dict'),
             marker=dict(default=""),
             max_keys=dict(default=1000, type='int'),
             metadata=dict(type='dict'),
             mode=dict(choices=[
                 'get', 'put', 'delete', 'create', 'geturl', 'getstr',
                 'delobj', 'list'
             ],
                       required=True),
             object=dict(),
             permission=dict(type='list', default=['private']),
             version=dict(default=None),
             overwrite=dict(aliases=['force'], default='always'),
             prefix=dict(default=""),
             retries=dict(aliases=['retry'], type='int', default=0),
             s3_url=dict(aliases=['S3_URL']),
             dualstack=dict(default='no', type='bool'),
             rgw=dict(default='no', type='bool'),
             src=dict(),
             ignore_nonexistent_bucket=dict(default=False, type='bool'),
             encryption_kms_key_id=dict()), )
    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[['mode', 'put', ['src', 'object']],
                     ['mode', 'get', ['dest', 'object']],
                     ['mode', 'getstr', ['object']],
                     ['mode', 'geturl', ['object']]],
    )

    if module._name == 's3':
        module.deprecate("The 's3' module is being renamed 'aws_s3'",
                         version=2.7)

    bucket = module.params.get('bucket')
    encrypt = module.params.get('encrypt')
    expiry = module.params.get('expiry')
    dest = module.params.get('dest', '')
    headers = module.params.get('headers')
    marker = module.params.get('marker')
    max_keys = module.params.get('max_keys')
    metadata = module.params.get('metadata')
    mode = module.params.get('mode')
    obj = module.params.get('object')
    version = module.params.get('version')
    overwrite = module.params.get('overwrite')
    prefix = module.params.get('prefix')
    retries = module.params.get('retries')
    s3_url = module.params.get('s3_url')
    dualstack = module.params.get('dualstack')
    rgw = module.params.get('rgw')
    src = module.params.get('src')
    ignore_nonexistent_bucket = module.params.get('ignore_nonexistent_bucket')

    object_canned_acl = [
        "private", "public-read", "public-read-write", "aws-exec-read",
        "authenticated-read", "bucket-owner-read", "bucket-owner-full-control"
    ]
    bucket_canned_acl = [
        "private", "public-read", "public-read-write", "authenticated-read"
    ]

    if overwrite not in ['always', 'never', 'different']:
        if module.boolean(overwrite):
            overwrite = 'always'
        else:
            overwrite = 'never'

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module,
                                                                  boto3=True)

    if region in ('us-east-1', '', None):
        # default to US Standard region
        location = 'us-east-1'
    else:
        # Boto uses symbolic names for locations but region strings will
        # actually work fine for everything except us-east-1 (US Standard)
        location = region

    if module.params.get('object'):
        obj = module.params['object']
        # If there is a top level object, do nothing - if the object starts with /
        # remove the leading character to maintain compatibility with Ansible versions < 2.4
        if obj.startswith('/'):
            obj = obj[1:]

    # Bucket deletion does not require obj.  Prevents ambiguity with delobj.
    if obj and mode == "delete":
        module.fail_json(msg='Parameter obj cannot be used with mode=delete')

    # allow eucarc environment variables to be used if ansible vars aren't set
    if not s3_url and 'S3_URL' in os.environ:
        s3_url = os.environ['S3_URL']

    if dualstack and s3_url is not None and 'amazonaws.com' not in s3_url:
        module.fail_json(msg='dualstack only applies to AWS S3')

    if dualstack and not module.botocore_at_least('1.4.45'):
        module.fail_json(msg='dualstack requires botocore >= 1.4.45')

    # rgw requires an explicit url
    if rgw and not s3_url:
        module.fail_json(msg='rgw flavour requires s3_url')

    # Look at s3_url and tweak connection settings
    # if connecting to RGW, Walrus or fakes3
    if s3_url:
        for key in ['validate_certs', 'security_token', 'profile_name']:
            aws_connect_kwargs.pop(key, None)
    s3 = get_s3_connection(module, aws_connect_kwargs, location, rgw, s3_url)

    validate = not ignore_nonexistent_bucket

    # separate types of ACLs
    bucket_acl = [
        acl for acl in module.params.get('permission')
        if acl in bucket_canned_acl
    ]
    object_acl = [
        acl for acl in module.params.get('permission')
        if acl in object_canned_acl
    ]
    error_acl = [
        acl for acl in module.params.get('permission')
        if acl not in bucket_canned_acl and acl not in object_canned_acl
    ]
    if error_acl:
        module.fail_json(msg='Unknown permission specified: %s' % error_acl)

    # First, we check to see if the bucket exists, we get "bucket" returned.
    bucketrtn = bucket_check(module, s3, bucket, validate=validate)

    if validate and mode not in ('create', 'put', 'delete') and not bucketrtn:
        module.fail_json(msg="Source bucket cannot be found.")

    # If our mode is a GET operation (download), go through the procedure as appropriate ...
    if mode == 'get':
        # Next, we check to see if the key in the bucket exists. If it exists, it also returns key_matches md5sum check.
        keyrtn = key_check(module,
                           s3,
                           bucket,
                           obj,
                           version=version,
                           validate=validate)
        if keyrtn is False:
            if version:
                module.fail_json(
                    msg="Key %s with version id %s does not exist." %
                    (obj, version))
            else:
                module.fail_json(msg="Key %s does not exist." % obj)

        # If the destination path doesn't exist or overwrite is True, no need to do the md5sum ETag check, so just download.
        # Compare the remote MD5 sum of the object with the local dest md5sum, if it already exists.
        if path_check(dest):
            # Determine if the remote and local object are identical
            if keysum_compare(module, dest, s3, bucket, obj, version=version):
                sum_matches = True
                if overwrite == 'always':
                    try:
                        download_s3file(module,
                                        s3,
                                        bucket,
                                        obj,
                                        dest,
                                        retries,
                                        version=version)
                    except Sigv4Required:
                        s3 = get_s3_connection(module,
                                               aws_connect_kwargs,
                                               location,
                                               rgw,
                                               s3_url,
                                               sig_4=True)
                        download_s3file(module,
                                        s3,
                                        bucket,
                                        obj,
                                        dest,
                                        retries,
                                        version=version)
                else:
                    module.exit_json(
                        msg=
                        "Local and remote object are identical, ignoring. Use overwrite=always parameter to force.",
                        changed=False)
            else:
                sum_matches = False

                if overwrite in ('always', 'different'):
                    try:
                        download_s3file(module,
                                        s3,
                                        bucket,
                                        obj,
                                        dest,
                                        retries,
                                        version=version)
                    except Sigv4Required:
                        s3 = get_s3_connection(module,
                                               aws_connect_kwargs,
                                               location,
                                               rgw,
                                               s3_url,
                                               sig_4=True)
                        download_s3file(module,
                                        s3,
                                        bucket,
                                        obj,
                                        dest,
                                        retries,
                                        version=version)
                else:
                    module.exit_json(
                        msg=
                        "WARNING: Checksums do not match. Use overwrite parameter to force download."
                    )
        else:
            try:
                download_s3file(module,
                                s3,
                                bucket,
                                obj,
                                dest,
                                retries,
                                version=version)
            except Sigv4Required:
                s3 = get_s3_connection(module,
                                       aws_connect_kwargs,
                                       location,
                                       rgw,
                                       s3_url,
                                       sig_4=True)
                download_s3file(module,
                                s3,
                                bucket,
                                obj,
                                dest,
                                retries,
                                version=version)

    # if our mode is a PUT operation (upload), go through the procedure as appropriate ...
    if mode == 'put':

        # if putting an object in a bucket yet to be created, acls for the bucket and/or the object may be specified
        # these were separated into the variables bucket_acl and object_acl above

        # Lets check the src path.
        if not path_check(src):
            module.fail_json(msg="Local object for PUT does not exist")

        # Lets check to see if bucket exists to get ground truth.
        if bucketrtn:
            keyrtn = key_check(module,
                               s3,
                               bucket,
                               obj,
                               version=version,
                               validate=validate)

        # Lets check key state. Does it exist and if it does, compute the ETag md5sum.
        if bucketrtn and keyrtn:
            # Compare the local and remote object
            if keysum_compare(module, src, s3, bucket, obj):
                sum_matches = True
                if overwrite == 'always':
                    # only use valid object acls for the upload_s3file function
                    module.params['permission'] = object_acl
                    upload_s3file(module, s3, bucket, obj, src, expiry,
                                  metadata, encrypt, headers)
                else:
                    get_download_url(module,
                                     s3,
                                     bucket,
                                     obj,
                                     expiry,
                                     changed=False)
            else:
                sum_matches = False
                if overwrite in ('always', 'different'):
                    # only use valid object acls for the upload_s3file function
                    module.params['permission'] = object_acl
                    upload_s3file(module, s3, bucket, obj, src, expiry,
                                  metadata, encrypt, headers)
                else:
                    module.exit_json(
                        msg=
                        "WARNING: Checksums do not match. Use overwrite parameter to force upload."
                    )

        # If neither exist (based on bucket existence), we can create both.
        if not bucketrtn:
            # only use valid bucket acls for create_bucket function
            module.params['permission'] = bucket_acl
            create_bucket(module, s3, bucket, location)
            # only use valid object acls for the upload_s3file function
            module.params['permission'] = object_acl
            upload_s3file(module, s3, bucket, obj, src, expiry, metadata,
                          encrypt, headers)

        # If bucket exists but key doesn't, just upload.
        if bucketrtn and not keyrtn:
            # only use valid object acls for the upload_s3file function
            module.params['permission'] = object_acl
            upload_s3file(module, s3, bucket, obj, src, expiry, metadata,
                          encrypt, headers)

    # Delete an object from a bucket, not the entire bucket
    if mode == 'delobj':
        if obj is None:
            module.fail_json(msg="object parameter is required")
        if bucket:
            deletertn = delete_key(module, s3, bucket, obj)
            if deletertn is True:
                module.exit_json(msg="Object deleted from bucket %s." % bucket,
                                 changed=True)
        else:
            module.fail_json(msg="Bucket parameter is required.")

    # Delete an entire bucket, including all objects in the bucket
    if mode == 'delete':
        if bucket:
            deletertn = delete_bucket(module, s3, bucket)
            if deletertn is True:
                module.exit_json(
                    msg="Bucket %s and all keys have been deleted." % bucket,
                    changed=True)
        else:
            module.fail_json(msg="Bucket parameter is required.")

    # Support for listing a set of keys
    if mode == 'list':
        exists = bucket_check(module, s3, bucket)

        # If the bucket does not exist then bail out
        if not exists:
            module.fail_json(msg="Target bucket (%s) cannot be found" % bucket)

        list_keys(module, s3, bucket, prefix, marker, max_keys)

    # Need to research how to create directories without "populating" a key, so this should just do bucket creation for now.
    # WE SHOULD ENABLE SOME WAY OF CREATING AN EMPTY KEY TO CREATE "DIRECTORY" STRUCTURE, AWS CONSOLE DOES THIS.
    if mode == 'create':

        # if both creating a bucket and putting an object in it, acls for the bucket and/or the object may be specified
        # these were separated above into the variables bucket_acl and object_acl

        if bucket and not obj:
            if bucketrtn:
                module.exit_json(msg="Bucket already exists.", changed=False)
            else:
                # only use valid bucket acls when creating the bucket
                module.params['permission'] = bucket_acl
                module.exit_json(msg="Bucket created successfully",
                                 changed=create_bucket(module, s3, bucket,
                                                       location))
        if bucket and obj:
            if obj.endswith('/'):
                dirobj = obj
            else:
                dirobj = obj + "/"
            if bucketrtn:
                if key_check(module, s3, bucket, dirobj):
                    module.exit_json(
                        msg="Bucket %s and key %s already exists." %
                        (bucket, obj),
                        changed=False)
                else:
                    # setting valid object acls for the create_dirkey function
                    module.params['permission'] = object_acl
                    create_dirkey(module, s3, bucket, dirobj, encrypt)
            else:
                # only use valid bucket acls for the create_bucket function
                module.params['permission'] = bucket_acl
                created = create_bucket(module, s3, bucket, location)
                # only use valid object acls for the create_dirkey function
                module.params['permission'] = object_acl
                create_dirkey(module, s3, bucket, dirobj, encrypt)

    # Support for grabbing the time-expired URL for an object in S3/Walrus.
    if mode == 'geturl':
        if not bucket and not obj:
            module.fail_json(msg="Bucket and Object parameters must be set")

        keyrtn = key_check(module,
                           s3,
                           bucket,
                           obj,
                           version=version,
                           validate=validate)
        if keyrtn:
            get_download_url(module, s3, bucket, obj, expiry)
        else:
            module.fail_json(msg="Key %s does not exist." % obj)

    if mode == 'getstr':
        if bucket and obj:
            keyrtn = key_check(module,
                               s3,
                               bucket,
                               obj,
                               version=version,
                               validate=validate)
            if keyrtn:
                try:
                    download_s3str(module, s3, bucket, obj, version=version)
                except Sigv4Required:
                    s3 = get_s3_connection(module,
                                           aws_connect_kwargs,
                                           location,
                                           rgw,
                                           s3_url,
                                           sig_4=True)
                    download_s3str(module, s3, bucket, obj, version=version)
            elif version is not None:
                module.fail_json(
                    msg="Key %s with version id %s does not exist." %
                    (obj, version))
            else:
                module.fail_json(msg="Key %s does not exist." % obj)

    module.exit_json(failed=False)
Beispiel #30
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        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)