コード例 #1
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)
コード例 #2
0
def main():
    argument_spec = dict(filters=dict(default={}, type='dict'))

    module = AnsibleAWSModule(argument_spec=argument_spec)
    if module._name == 'aws_az_facts':
        module.deprecate(
            "The 'aws_az_facts' module has been renamed to 'aws_az_info'",
            version='2.14')

    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:
        availability_zones = connection.describe_availability_zones(
            Filters=ansible_dict_to_boto3_filter_list(sanitized_filters))
    except (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e, msg="Unable to describe availability zones.")

    # Turn the boto3 result into ansible_friendly_snaked_names
    snaked_availability_zones = [
        camel_dict_to_snake_dict(az)
        for az in availability_zones['AvailabilityZones']
    ]

    module.exit_json(availability_zones=snaked_availability_zones)
コード例 #3
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))
コード例 #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)
コード例 #5
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')

    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)
コード例 #6
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(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))
コード例 #7
0
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)
コード例 #8
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))
コード例 #9
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)
コード例 #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)
コード例 #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)
コード例 #12
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))
コード例 #13
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))
コード例 #14
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)
コード例 #15
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))
コード例 #16
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)
コード例 #17
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()
コード例 #18
0
def main():
    """
    Module action handler
    """
    argument_spec = 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')

    connection = EFSConnection(module)

    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)
コード例 #19
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
    ])
コード例 #20
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)
コード例 #21
0
def main():

    argument_spec = 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)
コード例 #22
0
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])
コード例 #23
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']])
コード例 #24
0
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)
コード例 #25
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)
コード例 #26
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)
コード例 #27
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)