예제 #1
0
def main():

    argument_spec = (
        dict(
            catalog_id=dict(type='str'),
            connection_properties=dict(type='dict'),
            connection_type=dict(type='str', default='JDBC', choices=['JDBC', 'SFTP']),
            description=dict(type='str'),
            match_criteria=dict(type='list'),
            name=dict(required=True, type='str'),
            security_groups=dict(type='list'),
            state=dict(required=True, choices=['present', 'absent'], type='str'),
            subnet_id=dict(type='str')
        )
    )

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[
                                  ('state', 'present', ['connection_properties'])
                              ]
                              )

    connection_glue = module.client('glue')
    connection_ec2 = module.client('ec2')

    glue_connection = _get_glue_connection(connection_glue, module)

    if module.params.get("state") == 'present':
        create_or_update_glue_connection(connection_glue, connection_ec2, module, glue_connection)
    else:
        delete_glue_connection(connection_glue, module, glue_connection)
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(
        iam_type=dict(required=True, choices=['user', 'group', 'role']),
        iam_name=dict(required=True),
        policy_name=dict(default=None, required=False),
    )

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

    args = dict(
        client=module.client('iam'),
        name=module.params.get('iam_name'),
        policy_name=module.params.get('policy_name'),
    )
    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:
        if e.response['Error']['Code'] == 'NoSuchEntity':
            module.exit_json(changed=False, msg=e.response['Error']['Message'])
        module.fail_json_aws(e)
    except PolicyError as e:
        module.fail_json(msg=str(e))
예제 #4
0
def main():
    argument_spec = dict(
        name=dict(type='str', required=True),
        state=dict(type='str',
                   default='present',
                   choices=['present', 'absent']),
        active=dict(type='bool'),
        force=dict(type='bool', default=False),
    )

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

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

    # SES APIs seem to have a much lower throttling threshold than most of the rest of the AWS APIs.
    # Docs say 1 call per second. This shouldn't actually be a big problem for normal usage, but
    # the ansible build runs multiple instances of the test in parallel that's caused throttling
    # failures so apply a jittered backoff to call SES calls.
    client = module.client('ses', retry_decorator=AWSRetry.jittered_backoff())

    if state == 'absent':
        remove_rule_set(client, module)
    else:
        create_or_update_rule_set(client, module)
def main():

    argument_spec = (
        dict(
            allocated_capacity=dict(type='int'),
            command_name=dict(type='str', default='glueetl'),
            command_script_location=dict(type='str'),
            connections=dict(type='list'),
            default_arguments=dict(type='dict'),
            description=dict(type='str'),
            max_concurrent_runs=dict(type='int'),
            max_retries=dict(type='int'),
            name=dict(required=True, type='str'),
            role=dict(type='str'),
            state=dict(required=True, choices=['present', 'absent'], type='str'),
            timeout=dict(type='int')
        )
    )

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[
                                  ('state', 'present', ['role', 'command_script_location'])
                              ]
                              )

    connection = module.client('glue')

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

    glue_job = _get_glue_job(connection, module, module.params.get("name"))

    if state == 'present':
        create_or_update_glue_job(connection, module, glue_job)
    else:
        delete_glue_job(connection, module, glue_job)
def main():
    argument_spec = dict(
        name=dict(required=True),
        schedule_expression=dict(),
        event_pattern=dict(),
        state=dict(choices=['present', 'disabled', 'absent'],
                   default='present'),
        description=dict(),
        role_arn=dict(),
        targets=dict(type='list', default=[]),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec)

    rule_data = dict([(rf, module.params.get(rf))
                      for rf in CloudWatchEventRuleManager.RULE_FIELDS])
    targets = module.params.get('targets')
    state = module.params.get('state')
    client = module.client('events')

    cwe_rule = CloudWatchEventRule(module, client=client, **rule_data)
    cwe_rule_manager = CloudWatchEventRuleManager(cwe_rule, targets)

    if state == 'present':
        cwe_rule_manager.ensure_present()
    elif state == 'disabled':
        cwe_rule_manager.ensure_disabled()
    elif state == 'absent':
        cwe_rule_manager.ensure_absent()
    else:
        module.fail_json(msg="Invalid state '{0}' provided".format(state))

    module.exit_json(**cwe_rule_manager.fetch_aws_state())
예제 #7
0
def main():

    argument_spec = dict(
        name=dict(required=True),
        managed_policies=dict(default=[],
                              type='list',
                              aliases=['managed_policy']),
        users=dict(default=[], type='list'),
        state=dict(choices=['present', 'absent'], required=True),
        purge_users=dict(default=False, type='bool'),
        purge_policies=dict(default=False,
                            type='bool',
                            aliases=['purge_policy',
                                     'purge_managed_policies']))

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

    connection = module.client('iam')

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

    if state == 'present':
        create_or_update_group(connection, module)
    else:
        destroy_group(connection, module)
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)
def main():
    argument_spec = dict(name=dict(required=True),
                         description=dict(),
                         source=dict(required=True, type='dict'),
                         artifacts=dict(required=True, type='dict'),
                         cache=dict(type='dict'),
                         environment=dict(type='dict'),
                         service_role=dict(),
                         timeout_in_minutes=dict(type='int', default=60),
                         encryption_key=dict(),
                         tags=dict(type='list'),
                         vpc_config=dict(type='dict'),
                         state=dict(choices=['present', 'absent'],
                                    default='present'))

    module = AnsibleAWSModule(argument_spec=argument_spec)
    client_conn = module.client('codebuild')

    state = module.params.get('state')
    changed = False

    if state == 'present':
        project_result, changed = create_or_update_project(
            client=client_conn, params=module.params, module=module)
    elif state == 'absent':
        project_result, changed = delete_project(client=client_conn,
                                                 name=module.params['name'],
                                                 module=module)

    module.exit_json(changed=changed,
                     **camel_dict_to_snake_dict(project_result))
def main():
    module = AnsibleAWSModule(
        argument_spec={
            'state': dict(type='str', choices=['present', 'absent'], default='present'),
            'authorized_account_id': dict(type='str', required=True),
            'authorized_aws_region': dict(type='str', required=True),
        },
        supports_check_mode=False,
    )

    result = {'changed': False}

    params = {
        'AuthorizedAccountId': module.params.get('authorized_account_id'),
        'AuthorizedAwsRegion': module.params.get('authorized_aws_region'),
    }

    client = module.client('config', retry_decorator=AWSRetry.jittered_backoff())
    resource_status = resource_exists(client, module, params)

    if module.params.get('state') == 'present':
        if not resource_status:
            create_resource(client, module, params, result)
        else:
            update_resource(client, module, params, result)

    if module.params.get('state') == 'absent':
        if resource_status:
            delete_resource(client, module, params, result)

    module.exit_json(changed=result['changed'])
예제 #11
0
def main():
    argument_spec = dict(
        name=dict(required=True, type='str'),
        metric=dict(type='str'),
        namespace=dict(type='str'),
        statistic=dict(type='str', choices=['SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum']),
        comparison=dict(type='str', choices=['LessThanOrEqualToThreshold', 'LessThanThreshold', 'GreaterThanThreshold',
                                             'GreaterThanOrEqualToThreshold', '<=', '<', '>', '>=']),
        threshold=dict(type='float'),
        period=dict(type='int'),
        unit=dict(type='str', choices=['Seconds', 'Microseconds', 'Milliseconds', 'Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes',
                                       'Terabytes', 'Bits', 'Kilobits', 'Megabits', 'Gigabits', 'Terabits', 'Percent', 'Count',
                                       'Bytes/Second', 'Kilobytes/Second', 'Megabytes/Second', 'Gigabytes/Second',
                                       'Terabytes/Second', 'Bits/Second', 'Kilobits/Second', 'Megabits/Second', 'Gigabits/Second',
                                       'Terabits/Second', 'Count/Second', 'None']),
        evaluation_periods=dict(type='int'),
        description=dict(type='str'),
        dimensions=dict(type='dict', default={}),
        alarm_actions=dict(type='list', default=[]),
        insufficient_data_actions=dict(type='list', default=[]),
        ok_actions=dict(type='list', default=[]),
        treat_missing_data=dict(type='str', choices=['breaching', 'notBreaching', 'ignore', 'missing'], default='missing'),
        state=dict(default='present', choices=['present', 'absent']),
    )

    module = AnsibleAWSModule(argument_spec=argument_spec)

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

    connection = module.client('cloudwatch')

    if state == 'present':
        create_metric_alarm(connection, module)
    elif state == 'absent':
        delete_metric_alarm(connection, module)
def main():
    module = AnsibleAWSModule(
        argument_spec={
            'identity': dict(required=True, type='str'),
            'state': dict(default='present', choices=['present', 'absent']),
            'policy_name': dict(required=True, type='str'),
            'policy': dict(type='json', default=None),
        },
        required_if=[['state', 'present', ['policy']]],
        supports_check_mode=True,
    )

    # SES APIs seem to have a much lower throttling threshold than most of the rest of the AWS APIs.
    # Docs say 1 call per second. This shouldn't actually be a big problem for normal usage, but
    # the ansible build runs multiple instances of the test in parallel that's caused throttling
    # failures so apply a jittered backoff to call SES calls.
    connection = module.client('ses',
                               retry_decorator=AWSRetry.jittered_backoff())

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

    if state == 'present':
        create_or_update_identity_policy(connection, module)
    else:
        delete_identity_policy(connection, module)
def main():
    argument_spec = dict(
        autoscaling_group_name=dict(required=True, type='str'),
        lifecycle_hook_name=dict(required=True, type='str'),
        transition=dict(type='str',
                        choices=[
                            'autoscaling:EC2_INSTANCE_TERMINATING',
                            'autoscaling:EC2_INSTANCE_LAUNCHING'
                        ]),
        role_arn=dict(type='str'),
        notification_target_arn=dict(type='str'),
        notification_meta_data=dict(type='str'),
        heartbeat_timeout=dict(type='int'),
        default_result=dict(default='ABANDON', choices=['ABANDON',
                                                        'CONTINUE']),
        state=dict(default='present', choices=['present', 'absent']))

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        required_if=[['state', 'present', ['transition']]])
    state = module.params.get('state')

    connection = module.client('autoscaling')

    changed = False

    if state == 'present':
        changed = create_lifecycle_hook(connection, module)
    elif state == 'absent':
        changed = delete_lifecycle_hook(connection, module)

    module.exit_json(changed=changed)
def main():
    module = AnsibleAWSModule(
        argument_spec={
            'name':
            dict(type='str', required=True),
            'state':
            dict(type='str', choices=['present', 'absent'], default='present'),
            's3_bucket':
            dict(type='str', required=True),
            's3_prefix':
            dict(type='str'),
            'sns_topic_arn':
            dict(type='str'),
            'delivery_frequency':
            dict(type='str',
                 choices=[
                     'One_Hour', 'Three_Hours', 'Six_Hours', 'Twelve_Hours',
                     'TwentyFour_Hours'
                 ]),
        },
        supports_check_mode=False,
    )

    result = {'changed': False}

    name = module.params.get('name')
    state = module.params.get('state')

    params = {}
    if name:
        params['name'] = name
    if module.params.get('s3_bucket'):
        params['s3BucketName'] = module.params.get('s3_bucket')
    if module.params.get('s3_prefix'):
        params['s3KeyPrefix'] = module.params.get('s3_prefix')
    if module.params.get('sns_topic_arn'):
        params['snsTopicARN'] = module.params.get('sns_topic_arn')
    if module.params.get('delivery_frequency'):
        params['configSnapshotDeliveryProperties'] = {
            'deliveryFrequency': module.params.get('delivery_frequency')
        }

    client = module.client('config',
                           retry_decorator=AWSRetry.jittered_backoff())

    resource_status = resource_exists(client, module, params)

    if state == 'present':
        if not resource_status:
            create_resource(client, module, params, result)
        if resource_status:
            update_resource(client, module, params, result)

    if state == 'absent':
        if resource_status:
            delete_resource(client, module, params, result)

    module.exit_json(**result)
예제 #15
0
def main():
    argument_spec = dict(name=dict(required=True, type='str'),
                         role_arn=dict(required=True, type='str'),
                         artifact_store=dict(required=True, type='dict'),
                         stages=dict(required=True, type='list'),
                         version=dict(type='int'),
                         state=dict(choices=['present', 'absent'],
                                    default='present'))

    module = AnsibleAWSModule(argument_spec=argument_spec)
    client_conn = module.client('codepipeline')

    state = module.params.get('state')
    changed = False

    # Determine if the CodePipeline exists
    found_code_pipeline = describe_pipeline(client=client_conn,
                                            name=module.params['name'],
                                            version=module.params['version'],
                                            module=module)
    pipeline_result = {}

    if state == 'present':
        if 'pipeline' in found_code_pipeline:
            pipeline_dict = copy.deepcopy(found_code_pipeline['pipeline'])
            # Update dictionary with provided module params:
            pipeline_dict['roleArn'] = module.params['role_arn']
            pipeline_dict['artifactStore'] = module.params['artifact_store']
            pipeline_dict['stages'] = module.params['stages']
            if module.params['version'] is not None:
                pipeline_dict['version'] = module.params['version']

            pipeline_result = update_pipeline(client=client_conn,
                                              pipeline_dict=pipeline_dict,
                                              module=module)

            if compare_policies(found_code_pipeline['pipeline'],
                                pipeline_result['pipeline']):
                changed = True
        else:
            pipeline_result = create_pipeline(
                client=client_conn,
                name=module.params['name'],
                role_arn=module.params['role_arn'],
                artifact_store=module.params['artifact_store'],
                stages=module.params['stages'],
                version=module.params['version'],
                module=module)
            changed = True
    elif state == 'absent':
        if found_code_pipeline:
            pipeline_result = delete_pipeline(client=client_conn,
                                              name=module.params['name'],
                                              module=module)
            changed = True

    module.exit_json(changed=changed,
                     **camel_dict_to_snake_dict(pipeline_result))
예제 #16
0
def main():
    argument_spec = dict(name=dict(), group=dict(), path=dict(default='/'))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              mutually_exclusive=[['group', 'path']],
                              supports_check_mode=True)

    connection = module.client('iam')

    list_iam_users(connection, module)
예제 #17
0
def main():
    argument_spec = dict(
        api_id=dict(type='str', required=False),
        state=dict(type='str', default='present', choices=['present', 'absent']),
        swagger_file=dict(type='path', default=None, aliases=['src', 'api_file']),
        swagger_dict=dict(type='json', default=None),
        swagger_text=dict(type='str', default=None),
        stage=dict(type='str', default=None),
        deploy_desc=dict(type='str', default="Automatic deployment by Ansible."),
    )

    mutually_exclusive = [['swagger_file', 'swagger_dict', 'swagger_text']]  # noqa: F841

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

    api_id = module.params.get('api_id')
    state = module.params.get('state')   # noqa: F841
    swagger_file = module.params.get('swagger_file')
    swagger_dict = module.params.get('swagger_dict')
    swagger_text = module.params.get('swagger_text')
    stage = module.params.get('stage')
    deploy_desc = module.params.get('deploy_desc')

    client = module.client('apigateway')

    changed = True   # for now it will stay that way until we can sometimes avoid change
    conf_res = None
    dep_res = None
    del_res = None

    if state == "present":
        if api_id is None:
            api_id = create_empty_api(module, client)
        api_data = get_api_definitions(module, swagger_file=swagger_file,
                                       swagger_dict=swagger_dict, swagger_text=swagger_text)
        conf_res, dep_res = ensure_api_in_correct_state(module, client, api_id=api_id,
                                                        api_data=api_data, stage=stage,
                                                        deploy_desc=deploy_desc)
    if state == "absent":
        del_res = delete_rest_api(module, client, api_id)

    exit_args = {"changed": changed, "api_id": api_id}

    if conf_res is not None:
        exit_args['configure_response'] = camel_dict_to_snake_dict(conf_res)
    if dep_res is not None:
        exit_args['deploy_response'] = camel_dict_to_snake_dict(dep_res)
    if del_res is not None:
        exit_args['delete_response'] = camel_dict_to_snake_dict(del_res)

    module.exit_json(**exit_args)
예제 #18
0
def main():
    argument_spec = dict(
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        identifier=dict(type='str', required=True),
        description=dict(type='str', required=True),
        subnet_ids=dict(type='list', elements='str', required=True),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=True)
    exit_message = None
    changed = False

    state = module.params.get('state')
    dmsclient = module.client('dms')
    subnet_group = describe_subnet_group(dmsclient,
                                         module.params.get('identifier'))
    if state == 'present':
        if replication_subnet_exists(subnet_group):
            if compare_params(module,
                              subnet_group["ReplicationSubnetGroups"][0]):
                if not module.check_mode:
                    exit_message = modify_replication_subnet_group(
                        module, dmsclient)
                else:
                    exit_message = dmsclient
                changed = True
            else:
                exit_message = "No changes to Subnet group"
        else:
            if not module.check_mode:
                exit_message = create_replication_subnet_group(
                    module, dmsclient)
                changed = True
            else:
                exit_message = "Check mode enabled"

    elif state == 'absent':
        if replication_subnet_exists(subnet_group):
            if not module.check_mode:
                replication_subnet_group_delete(module, dmsclient)
                changed = True
                exit_message = "Replication subnet group Deleted"
            else:
                exit_message = dmsclient
                changed = True

        else:
            changed = False
            exit_message = "Replication subnet group does not exist"

    module.exit_json(changed=changed, msg=exit_message)
def run_module():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            cluster_name=dict(type='str', required=True, aliases=['cluster']),
            state=dict(type='str',
                       choices=['present', 'absent'],
                       default='present'),
            region=dict(type='str', required=True, aliases=['source']),
            destination_region=dict(type='str',
                                    required=True,
                                    aliases=['destination']),
            snapshot_copy_grant=dict(type='str', aliases=['copy_grant']),
            snapshot_retention_period=dict(type='int',
                                           required=True,
                                           aliases=['retention_period']),
        ))

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

    result = dict(changed=False, message='')
    connection = module.client('redshift')

    snapshot_controller = SnapshotController(
        client=connection, cluster_name=module.params.get('cluster_name'))

    current_config = snapshot_controller.get_cluster_snapshot_copy_status()
    if current_config is not None:
        if module.params.get('state') == 'present':
            if requesting_unsupported_modifications(current_config,
                                                    module.params):
                message = 'Cannot modify destination_region or grant_name. ' \
                          'Please disable cross-region snapshots, and re-run.'
                module.fail_json(msg=message, **result)
            if needs_update(current_config, module.params):
                result['changed'] = True
                if not module.check_mode:
                    snapshot_controller.modify_snapshot_copy_retention_period(
                        module.params.get('snapshot_retention_period'))
        else:
            result['changed'] = True
            if not module.check_mode:
                snapshot_controller.disable_snapshot_copy()
    else:
        if module.params.get('state') == 'present':
            result['changed'] = True
            if not module.check_mode:
                snapshot_controller.enable_snapshot_copy(
                    module.params.get('destination_region'),
                    module.params.get('snapshot_copy_grant'),
                    module.params.get('snapshot_retention_period'))
    module.exit_json(**result)
예제 #20
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))
예제 #21
0
def main():
    event_types = [
        's3:ObjectCreated:*', 's3:ObjectCreated:Put', 's3:ObjectCreated:Post',
        's3:ObjectCreated:Copy', 's3:ObjectCreated:CompleteMultipartUpload',
        's3:ObjectRemoved:*', 's3:ObjectRemoved:Delete',
        's3:ObjectRemoved:DeleteMarkerCreated', 's3:ObjectRestore:Post',
        's3:ObjectRestore:Completed', 's3:ReducedRedundancyLostObject'
    ]
    argument_spec = dict(
        state=dict(default='present', choices=['present', 'absent']),
        event_name=dict(required=True),
        lambda_function_arn=dict(aliases=['function_arn']),
        bucket_name=dict(required=True),
        events=dict(type='list', default=[], choices=event_types),
        prefix=dict(default=''),
        suffix=dict(default=''),
        lambda_alias=dict(),
        lambda_version=dict(type='int', default=0),
    )

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        mutually_exclusive=[['lambda_alias', 'lambda_version']],
        required_if=[['state', 'present', ['events']]])

    bucket = AmazonBucket(module.client('s3'), module.params['bucket_name'])
    current = bucket.current_config(module.params['event_name'])
    desired = Config.from_params(**module.params)
    notification_configuration = [cfg.raw for cfg in bucket.full_config()]

    state = module.params['state']
    try:
        if (state == 'present' and current == desired) or (state == 'absent'
                                                           and not current):
            changed = False
        elif module.check_mode:
            changed = True
        elif state == 'present':
            changed = True
            notification_configuration = bucket.apply_config(desired)
        elif state == 'absent':
            changed = True
            notification_configuration = bucket.delete_config(desired)
    except (ClientError, BotoCoreError) as e:
        module.fail_json(msg='{0}'.format(e))

    module.exit_json(**dict(changed=changed,
                            notification_configuration=[
                                camel_dict_to_snake_dict(cfg)
                                for cfg in notification_configuration
                            ]))
예제 #22
0
def main():
    argument_spec = dict(instance_id=dict(),
                         image_id=dict(),
                         architecture=dict(default='x86_64'),
                         kernel_id=dict(),
                         virtualization_type=dict(default='hvm'),
                         root_device_name=dict(),
                         delete_snapshot=dict(default=False, type='bool'),
                         name=dict(),
                         wait=dict(type='bool', default=False),
                         wait_timeout=dict(default=900, type='int'),
                         description=dict(default=''),
                         no_reboot=dict(default=False, type='bool'),
                         state=dict(default='present',
                                    choices=['present', 'absent']),
                         device_mapping=dict(type='list'),
                         tags=dict(type='dict'),
                         launch_permissions=dict(type='dict'),
                         image_location=dict(),
                         enhanced_networking=dict(type='bool'),
                         billing_products=dict(type='list'),
                         ramdisk_id=dict(),
                         sriov_net_support=dict(),
                         purge_tags=dict(type='bool', default=False))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[
                                  ['state', 'absent', ['image_id']],
                              ])

    # Using a required_one_of=[['name', 'image_id']] overrides the message that should be provided by
    # the required_if for state=absent, so check manually instead
    if not any([module.params['image_id'], module.params['name']]):
        module.fail_json(
            msg="one of the following is required: name, image_id")

    connection = module.client('ec2')

    if module.params.get('state') == 'absent':
        deregister_image(module, connection)
    elif module.params.get('state') == 'present':
        if module.params.get('image_id'):
            update_image(module, connection, module.params.get('image_id'))
        if not module.params.get('instance_id') and not module.params.get(
                'device_mapping'):
            module.fail_json(
                msg=
                "The parameters instance_id or device_mapping (register from EBS snapshot) are required for a new image."
            )
        create_image(module, connection)
def main():
    argument_spec = dict(state=dict(required=True,
                                    choices=['present', 'absent']),
                         name=dict(),
                         location=dict(),
                         bandwidth=dict(choices=['1Gbps', '10Gbps']),
                         link_aggregation_group=dict(),
                         connection_id=dict(),
                         forced_update=dict(type='bool', default=False))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_one_of=[('connection_id', 'name')],
                              required_if=[('state', 'present',
                                            ('location', 'bandwidth'))])

    connection = module.client('directconnect')

    state = module.params.get('state')
    try:
        connection_id = connection_exists(
            connection,
            connection_id=module.params.get('connection_id'),
            connection_name=module.params.get('name'))
        if not connection_id and module.params.get('connection_id'):
            module.fail_json(
                msg="The Direct Connect connection {0} does not exist.".format(
                    module.params.get('connection_id')))

        if state == 'present':
            changed, connection_id = ensure_present(
                connection,
                connection_id=connection_id,
                connection_name=module.params.get('name'),
                location=module.params.get('location'),
                bandwidth=module.params.get('bandwidth'),
                lag_id=module.params.get('link_aggregation_group'),
                forced_update=module.params.get('forced_update'))
            response = connection_status(connection, connection_id)
        elif state == 'absent':
            changed = ensure_absent(connection, connection_id)
            response = {}
    except DirectConnectError as e:
        if e.last_traceback:
            module.fail_json(msg=e.msg,
                             exception=e.last_traceback,
                             **camel_dict_to_snake_dict(e.exception.response))
        else:
            module.fail_json(msg=e.msg)

    module.exit_json(changed=changed, **camel_dict_to_snake_dict(response))
def main():
    filters_subspec = dict(
        country=dict(),
        field_to_match=dict(
            choices=['uri', 'query_string', 'header', 'method', 'body']),
        header=dict(),
        transformation=dict(choices=[
            'none', 'compress_white_space', 'html_entity_decode', 'lowercase',
            'cmd_line', 'url_decode'
        ]),
        position=dict(choices=[
            'exactly', 'starts_with', 'ends_with', 'contains', 'contains_word'
        ]),
        comparison=dict(choices=['EQ', 'NE', 'LE', 'LT', 'GE', 'GT']),
        target_string=dict(),  # Bytes
        size=dict(type='int'),
        ip_address=dict(),
        regex_pattern=dict(),
    )
    argument_spec = dict(
        name=dict(required=True),
        type=dict(required=True,
                  choices=['byte', 'geo', 'ip', 'regex', 'size', 'sql',
                           'xss']),
        filters=dict(type='list'),
        purge_filters=dict(type='bool', default=False),
        waf_regional=dict(type='bool', default=False),
        state=dict(default='present', choices=['present', 'absent']),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[['state', 'present', ['filters']]])
    state = module.params.get('state')

    resource = 'waf' if not module.params['waf_regional'] else 'waf-regional'
    client = module.client(resource)

    condition = Condition(client, module)

    if state == 'present':
        (changed, results) = condition.ensure_condition_present()
        # return a condition agnostic ID for use by aws_waf_rule
        results['ConditionId'] = results[condition.conditionsetid]
    else:
        (changed, results) = condition.ensure_condition_absent()

    module.exit_json(changed=changed,
                     condition=camel_dict_to_snake_dict(results))
def main():

    argument_spec = dict(customer_gateway_ids=dict(default=[], type='list'),
                         filters=dict(default={}, type='dict'))

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        mutually_exclusive=[['customer_gateway_ids', 'filters']],
        supports_check_mode=True)
    if module._module._name == 'ec2_customer_gateway_facts':
        module._module.deprecate(
            "The 'ec2_customer_gateway_facts' module has been renamed to 'ec2_customer_gateway_info'",
            version='2.13')

    connection = module.client('ec2')

    list_customer_gateways(connection, module)
예제 #26
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))
예제 #27
0
def main():
    protocols_list = [
        'http', 'https', 'tcp', 'tls', 'udp', 'tcp_udp', 'HTTP', 'HTTPS',
        'TCP', 'TLS', 'UDP', 'TCP_UDP'
    ]
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(deregistration_delay_timeout=dict(type='int'),
             health_check_protocol=dict(choices=protocols_list),
             health_check_port=dict(),
             health_check_path=dict(),
             health_check_interval=dict(type='int'),
             health_check_timeout=dict(type='int'),
             healthy_threshold_count=dict(type='int'),
             modify_targets=dict(default=True, type='bool'),
             name=dict(required=True),
             port=dict(type='int'),
             protocol=dict(choices=protocols_list),
             purge_tags=dict(default=True, type='bool'),
             stickiness_enabled=dict(type='bool'),
             stickiness_type=dict(default='lb_cookie'),
             stickiness_lb_cookie_duration=dict(type='int'),
             state=dict(required=True, choices=['present', 'absent']),
             successful_response_codes=dict(),
             tags=dict(default={}, type='dict'),
             target_type=dict(default='instance',
                              choices=['instance', 'ip', 'lambda']),
             targets=dict(type='list'),
             unhealthy_threshold_count=dict(type='int'),
             vpc_id=dict(),
             wait_timeout=dict(type='int', default=200),
             wait=dict(type='bool', default=False)))

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        required_if=[
            ['target_type', 'instance', ['protocol', 'port', 'vpc_id']],
            ['target_type', 'ip', ['protocol', 'port', 'vpc_id']],
        ])

    connection = module.client('elbv2')

    if module.params.get('state') == 'present':
        create_or_update_target_group(connection, module)
    else:
        delete_target_group(connection, module)
예제 #28
0
def main():

    argument_spec = dict(
        image_ids=dict(default=[], type='list', aliases=['image_id']),
        filters=dict(default={}, type='dict'),
        owners=dict(default=[], type='list', aliases=['owner']),
        executable_users=dict(default=[], type='list', aliases=['executable_user']),
        describe_image_attributes=dict(default=False, type='bool')
    )

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

    ec2_client = module.client('ec2')

    list_ec2_images(ec2_client, module)
예제 #29
0
def main():

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

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

    connection = module.client('ec2')

    list_ec2_vpc_nacls(connection, module)
def main():
    argument_spec = dict(source_region=dict(required=True),
                         source_image_id=dict(required=True),
                         name=dict(default='default'),
                         description=dict(default=''),
                         encrypted=dict(type='bool',
                                        default=False,
                                        required=False),
                         kms_key_id=dict(type='str', required=False),
                         wait=dict(type='bool', default=False),
                         wait_timeout=dict(type='int', default=600),
                         tags=dict(type='dict'),
                         tag_equality=dict(type='bool', default=False))

    module = AnsibleAWSModule(argument_spec=argument_spec)
    # TODO: Check botocore version
    ec2 = module.client('ec2')
    copy_image(module, ec2)