Beispiel #1
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=False, default=[], type='list'),
            sort=dict(required=False, default=None,
                      choices=['launch_configuration_name', 'image_id', 'created_time', 'instance_type', 'kernel_id', 'ramdisk_id', 'key_name']),
            sort_order=dict(required=False, default='ascending',
                            choices=['ascending', 'descending']),
            sort_start=dict(required=False, type='int'),
            sort_end=dict(required=False, type='int'),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)
    if module._name == 'ec2_lc_facts':
        module.deprecate("The 'ec2_lc_facts' module has been renamed to 'ec2_lc_info'", version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

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

    if region:
        connection = boto3_conn(module, conn_type='client', resource='autoscaling', region=region, endpoint=ec2_url, **aws_connect_params)
    else:
        module.fail_json(msg="region must be specified")

    list_launch_configs(connection, module)
Beispiel #2
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True, type='str'),
            adjustment_type=dict(type='str', choices=['ChangeInCapacity', 'ExactCapacity', 'PercentChangeInCapacity']),
            asg_name=dict(required=True, type='str'),
            scaling_adjustment=dict(type='int'),
            min_adjustment_step=dict(type='int'),
            cooldown=dict(type='int'),
            state=dict(default='present', choices=['present', 'absent']),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

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

    try:
        connection = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params)
    except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
        module.fail_json(msg=str(e))

    if state == 'present':
        create_scaling_policy(connection, module)
    elif state == 'absent':
        delete_scaling_policy(connection, module)
def main():

    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        name=dict(type='str'),
        tags=dict(type='dict'),
    ))
    module = AnsibleModule(argument_spec=argument_spec)
    if module._name == 'ec2_asg_facts':
        module.deprecate(
            "The 'ec2_asg_facts' module has been renamed to 'ec2_asg_info'",
            version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

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

    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(
            module, boto3=True)
        autoscaling = boto3_conn(module,
                                 conn_type='client',
                                 resource='autoscaling',
                                 region=region,
                                 endpoint=ec2_url,
                                 **aws_connect_kwargs)
    except ClientError as e:
        module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response))

    results = find_asgs(autoscaling, module, name=asg_name, tags=asg_tags)
    module.exit_json(results=results)
def main():
    """
    Main entry point.

    :return dict: changed, batch_job_queue_action, response
    """

    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            state=dict(required=False, default='present', choices=['present', 'absent']),
            job_queue_name=dict(required=True),
            job_queue_state=dict(required=False, default='ENABLED', choices=['ENABLED', 'DISABLED']),
            priority=dict(type='int', required=True),
            compute_environment_order=dict(type='list', required=True),
            region=dict(aliases=['aws_region', 'ec2_region'])
        )
    )

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

    # validate dependencies
    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required for this module.')

    aws = AWSConnection(module, ['batch'])

    validate_params(module, aws)

    results = manage_state(module, aws)

    module.exit_json(**camel_dict_to_snake_dict(results))
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(filters=dict(type='dict', default={}),
             dry_run=dict(type='bool', default=False, aliases=['DryRun']),
             dhcp_options_ids=dict(type='list', aliases=['DhcpOptionIds'])))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if module._name == 'ec2_vpc_dhcp_option_facts':
        module.deprecate(
            "The 'ec2_vpc_dhcp_option_facts' module has been renamed to 'ec2_vpc_dhcp_option_info'",
            version='2.13')

    # Validate Requirements
    if not HAS_BOTO3:
        module.fail_json(msg='boto3 and botocore are required.')

    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(
            module, boto3=True)
        connection = boto3_conn(module,
                                conn_type='client',
                                resource='ec2',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_kwargs)
    except botocore.exceptions.NoCredentialsError as e:
        module.fail_json(msg="Can't authorize connection - " + str(e))

    # call your function here
    results = list_dhcp_options(connection, module)

    module.exit_json(dhcp_options=results)
Beispiel #6
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(filters=dict(type='dict', default=dict()),
             vpn_gateway_ids=dict(type='list', default=None)))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if module._name == 'ec2_vpc_vgw_facts':
        module.deprecate(
            "The 'ec2_vpc_vgw_facts' module has been renamed to 'ec2_vpc_vgw_info'",
            version='2.13')

    # Validate Requirements
    if not HAS_BOTO3:
        module.fail_json(msg='json and boto3 is required.')

    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(
            module, boto3=True)
        connection = boto3_conn(module,
                                conn_type='client',
                                resource='ec2',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_kwargs)
    except botocore.exceptions.NoCredentialsError as e:
        module.fail_json(msg="Can't authorize connection - " + str(e))

    # call your function here
    results = list_virtual_gateways(connection, module)

    module.exit_json(virtual_gateways=results)
Beispiel #7
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            default_action=dict(choices=['block', 'allow', 'count']),
            metric_name=dict(),
            state=dict(default='present', choices=['present', 'absent']),
            rules=dict(type='list'),
            purge_rules=dict(type='bool', default=False),
            waf_regional=dict(type='bool', default=False),
        ),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[['state', 'present', ['default_action', 'rules']]])
    state = module.params.get('state')

    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)
    if state == 'present':
        (changed, results) = ensure_web_acl_present(client, module)
    else:
        (changed, results) = ensure_web_acl_absent(client, module)

    module.exit_json(changed=changed, web_acl=camel_dict_to_snake_dict(results))
Beispiel #8
0
def main():

    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            deregister_unused=dict(type='bool', default=False),
            target_az=dict(type='str'),
            target_group_arn=dict(type='str'),
            target_group_name=dict(type='str'),
            target_id=dict(type='str', required=True),
            target_port=dict(type='int'),
            target_status=dict(choices=['initial', 'healthy', 'unhealthy', 'unused', 'draining', 'unavailable'], type='str'),
            target_status_timeout=dict(type='int', default=60),
            state=dict(required=True, choices=['present', 'absent'], type='str'),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[['target_group_arn', 'target_group_name']]
                           )

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

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

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

    if state == 'present':
        register_target(connection, module)
    else:
        deregister_target(connection, module)
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(user_name=dict(required=False, default=None)))

    module = AnsibleModule(argument_spec=argument_spec)
    if module._name == 'iam_mfa_device_facts':
        module.deprecate(
            "The 'iam_mfa_device_facts' module has been renamed to 'iam_mfa_device_info'",
            version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module,
                                                                  boto3=True)
    if region:
        connection = boto3_conn(module,
                                conn_type='client',
                                resource='iam',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_kwargs)
    else:
        module.fail_json(msg="region must be specified")

    list_mfa_devices(connection, module)
Beispiel #10
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        log_group_name=dict(),
    ))

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
    if module._name == 'cloudwatchlogs_log_group_facts':
        module.deprecate("The 'cloudwatchlogs_log_group_facts' module has been renamed to 'cloudwatchlogs_log_group_info'", version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required.')

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

    desc_log_group = describe_log_group(client=logs,
                                        log_group_name=module.params['log_group_name'],
                                        module=module)
    final_log_group_snake = []

    for log_group in desc_log_group['logGroups']:
        final_log_group_snake.append(camel_dict_to_snake_dict(log_group))

    desc_log_group_result = dict(changed=False, log_groups=final_log_group_snake)
    module.exit_json(**desc_log_group_result)
Beispiel #11
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(duration_seconds=dict(required=False, default=None, type='int'),
             mfa_serial_number=dict(required=False, default=None),
             mfa_token=dict(required=False, default=None)))

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 and botocore are required.')

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module,
                                                                  boto3=True)
    if region:
        connection = boto3_conn(module,
                                conn_type='client',
                                resource='sts',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_kwargs)
    else:
        module.fail_json(msg="region must be specified")

    get_session_token(connection, module)
Beispiel #12
0
def main():

    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(name=dict(required=True),
             key_material=dict(),
             force=dict(type='bool', default=True),
             state=dict(default='present', choices=['present', 'absent']),
             wait=dict(type='bool', default=False),
             wait_timeout=dict(default=300, type='int')))

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

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

    ec2_client = boto3_conn(module,
                            conn_type='client',
                            resource='ec2',
                            region=region,
                            endpoint=ec2_url,
                            **aws_connect_params)

    name = module.params['name']
    state = module.params.get('state')
    key_material = module.params.get('key_material')
    force = module.params.get('force')

    if state == 'absent':
        delete_key_pair(module, ec2_client, name)
    elif state == 'present':
        create_key_pair(module, ec2_client, name, key_material, force)
Beispiel #13
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(names={'default': [], 'type': 'list'}))
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if module._name == 'ec2_elb_facts':
        module.deprecate(
            "The 'ec2_elb_facts' module has been renamed to 'ec2_elb_info'",
            version='2.13')

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    try:
        region, ec2_url, aws_connect_params = get_aws_connection_info(module)
        if not region:
            module.fail_json(msg="region must be specified")

        names = module.params['names']
        elb_information = ElbInformation(module, names, region,
                                         **aws_connect_params)

        ec2_info_result = dict(changed=False, elbs=elb_information.list_elbs())

    except BotoServerError as err:
        module.fail_json(msg="{0}: {1}".format(err.error_code,
                                               err.error_message),
                         exception=traceback.format_exc())

    module.exit_json(**ec2_info_result)
Beispiel #14
0
def main():
    argument_spec = ec2_argument_spec()

    argument_spec.update(
        dict(caller_reference=dict(),
             distribution_id=dict(),
             alias=dict(),
             target_paths=dict(required=True, type='list')))

    module = AnsibleAWSModule(argument_spec=argument_spec,
                              supports_check_mode=False,
                              mutually_exclusive=[['distribution_id',
                                                   'alias']])

    validation_mgr = CloudFrontInvalidationValidationManager(module)
    service_mgr = CloudFrontInvalidationServiceManager(module)

    caller_reference = module.params.get('caller_reference')
    distribution_id = module.params.get('distribution_id')
    alias = module.params.get('alias')
    target_paths = module.params.get('target_paths')

    result = {}

    distribution_id = validation_mgr.validate_distribution_id(
        distribution_id, alias)
    valid_target_paths = validation_mgr.validate_invalidation_batch(
        target_paths, caller_reference)
    valid_pascal_target_paths = snake_dict_to_camel_dict(
        valid_target_paths, True)
    result, changed = service_mgr.create_invalidation(
        distribution_id, valid_pascal_target_paths)

    module.exit_json(changed=changed, **camel_dict_to_snake_dict(result))
Beispiel #15
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        state=dict(default='present', choices=['present', 'absent']),
        name=dict(),
        vpn_gateway_id=dict(),
        vpc_id=dict(),
        asn=dict(type='int'),
        wait_timeout=dict(type='int', default=320),
        type=dict(default='ipsec.1', choices=['ipsec.1']),
        tags=dict(default=None, required=False, type='dict', aliases=['resource_tags']),
    )
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           required_if=[['state', 'present', ['name']]])

    if not HAS_BOTO3:
        module.fail_json(msg='json and boto3 is required.')

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

    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
        client = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs)
    except botocore.exceptions.NoCredentialsError as e:
        module.fail_json(msg="Can't authorize connection - %s" % to_native(e), exception=traceback.format_exc())

    if state == 'present':
        (changed, results) = ensure_vgw_present(client, module)
    else:
        (changed, results) = ensure_vgw_absent(client, module)
    module.exit_json(changed=changed, vgw=results)
Beispiel #16
0
def main():
    """
    Get list of S3 buckets
    :return:
    """

    # Ensure we have an empty dict
    result = {}

    # Including ec2 argument spec
    module = AnsibleModule(argument_spec=ec2_argument_spec(), supports_check_mode=True)
    is_old_facts = module._name == 'aws_s3_bucket_facts'
    if is_old_facts:
        module.deprecate("The 'aws_s3_bucket_facts' module has been renamed to 'aws_s3_bucket_info', "
                         "and the renamed one no longer returns ansible_facts", version='2.13')

    # Verify Boto3 is used
    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

    # Set up connection
    region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=HAS_BOTO3)
    connection = boto3_conn(module, conn_type='client', resource='s3', region=region, endpoint=ec2_url,
                            **aws_connect_params)

    # Gather results
    result['buckets'] = get_bucket_list(module, connection)

    # Send exit
    if is_old_facts:
        module.exit_json(msg="Retrieved s3 facts.", ansible_facts=result)
    else:
        module.exit_json(msg="Retrieved s3 info.", **result)
Beispiel #17
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(name=dict(type='str'), ))

    module = AnsibleModule(argument_spec=argument_spec, )
    if module._name == 'iam_server_certificate_facts':
        module.deprecate(
            "The 'iam_server_certificate_facts' module has been renamed to 'iam_server_certificate_info'",
            version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(
            module, boto3=True)
        iam = boto3_conn(module,
                         conn_type='client',
                         resource='iam',
                         region=region,
                         endpoint=ec2_url,
                         **aws_connect_kwargs)
    except botocore.exceptions.ClientError as e:
        module.fail_json(msg="Boto3 Client Error - " + str(e.msg))

    cert_name = module.params.get('name')
    results = get_server_certs(iam, cert_name)
    module.exit_json(results=results)
Beispiel #18
0
def main():

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

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

    if region:
        ec2_client = boto3_conn(module,
                                conn_type='client',
                                resource='ec2',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_params)
    else:
        module.fail_json(msg="region must be specified")

    list_ec2_images(ec2_client, module)
Beispiel #19
0
def main():

    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            snapshot_ids=dict(default=[], type='list'),
            owner_ids=dict(default=[], type='list'),
            restorable_by_user_ids=dict(default=[], type='list'),
            filters=dict(default={}, type='dict')
        )
    )

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[
                               ['snapshot_ids', 'owner_ids', 'restorable_by_user_ids', 'filters']
                           ]
                           )
    if module._name == 'ec2_snapshot_facts':
        module.deprecate("The 'ec2_snapshot_facts' module has been renamed to 'ec2_snapshot_info'", version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

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

    if region:
        connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params)
    else:
        module.fail_json(msg="region must be specified")

    list_ec2_snapshots(connection, module)
Beispiel #20
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(filters=dict(type='dict'),
             pending_deletion=dict(type='bool', default=False)))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if module._name == 'aws_kms_facts':
        module.deprecate(
            "The 'aws_kms_facts' module has been renamed to 'aws_kms_info'",
            version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 and botocore are required for this module')

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

    if region:
        connection = boto3_conn(module,
                                conn_type='client',
                                resource='kms',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_params)
    else:
        module.fail_json(msg="region must be specified")

    all_keys = get_kms_info(connection, module)
    module.exit_json(keys=[
        key for key in all_keys
        if key_matches_filters(key, module.params['filters'])
    ])
Beispiel #21
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(source_region=dict(required=True),
             source_snapshot_id=dict(required=True),
             description=dict(default=''),
             encrypted=dict(type='bool', default=False, required=False),
             kms_key_id=dict(type='str', required=False),
             wait=dict(type='bool', default=False),
             wait_timeout=dict(type='int', default=600),
             tags=dict(type='dict')))

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO3:
        module.fail_json(msg='botocore and boto3 are required.')

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

    copy_snapshot(module, client)
Beispiel #22
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(state=dict(default='present', choices=['present', 'absent']),
                              name=dict(),
                              amazon_asn=dict(),
                              virtual_gateway_id=dict(),
                              direct_connect_gateway_id=dict(),
                              wait_timeout=dict(type='int', default=320)))
    required_if = [('state', 'present', ['name', 'amazon_asn']),
                   ('state', 'absent', ['direct_connect_gateway_id'])]
    module = AnsibleModule(argument_spec=argument_spec,
                           required_if=required_if)

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required for this module')

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

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

    if state == 'present':
        (changed, results) = ensure_present(client, module)
    elif state == 'absent':
        changed = ensure_absent(client, module)
        results = {}

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

    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(load_balancer_arns=dict(type='list'), names=dict(type='list')))

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[['load_balancer_arns',
                                                'names']],
                           supports_check_mode=True)
    if module._name == 'elb_application_lb_facts':
        module.deprecate(
            "The 'elb_application_lb_facts' module has been renamed to 'elb_application_lb_info'",
            version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

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

    if region:
        connection = boto3_conn(module,
                                conn_type='client',
                                resource='elbv2',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_params)
    else:
        module.fail_json(msg="region must be specified")

    list_load_balancers(connection, module)
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(filters=dict(default=None, type='dict')))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if module._name == 'ec2_vpc_route_table_facts':
        module.deprecate(
            "The 'ec2_vpc_route_table_facts' module has been renamed to 'ec2_vpc_route_table_info'",
            version='2.13')

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

    if region:
        try:
            connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="region must be specified")

    list_ec2_vpc_route_tables(connection, module)
def main():

    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(name=dict(required=True, type='str'),
             rules=dict(type='list'),
             state=dict(type='str',
                        choices=['present', 'absent'],
                        required=True)))

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required.')

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

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

    if state == 'present':
        create_or_update_bucket_cors(client, module)
    elif state == 'absent':
        destroy_bucket_cors(client, module)
Beispiel #26
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        mode=dict(choices=['push'], default='push'),
        file_change_strategy=dict(choices=['force', 'date_size', 'checksum'], default='date_size'),
        bucket=dict(required=True),
        key_prefix=dict(required=False, default=''),
        file_root=dict(required=True, type='path'),
        permission=dict(required=False, choices=['private', 'public-read', 'public-read-write', 'authenticated-read',
                                                 'aws-exec-read', 'bucket-owner-read', 'bucket-owner-full-control']),
        retries=dict(required=False, removed_in_version='2.14'),
        mime_map=dict(required=False, type='dict'),
        exclude=dict(required=False, default=".*"),
        include=dict(required=False, default="*"),
        cache_control=dict(required=False, default=''),
        delete=dict(required=False, type='bool', default=False),
        # future options: encoding, metadata, storage_class, retries
    )
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
    )

    if not HAS_DATEUTIL:
        module.fail_json(msg='dateutil required for this module')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

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

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
    if not region:
        module.fail_json(msg="Region must be specified")
    s3 = boto3_conn(module, conn_type='client', resource='s3', region=region, endpoint=ec2_url, **aws_connect_kwargs)

    if mode == 'push':
        try:
            result['filelist_initial'] = gather_files(module.params['file_root'], exclude=module.params['exclude'], include=module.params['include'])
            result['filelist_typed'] = determine_mimetypes(result['filelist_initial'], module.params.get('mime_map'))
            result['filelist_s3'] = calculate_s3_path(result['filelist_typed'], module.params['key_prefix'])
            result['filelist_local_etag'] = calculate_local_etag(result['filelist_s3'])
            result['filelist_actionable'] = filter_list(s3, module.params['bucket'], result['filelist_local_etag'], module.params['file_change_strategy'])
            result['uploads'] = upload_files(s3, module.params['bucket'], result['filelist_actionable'], module.params)

            if module.params['delete']:
                result['removed'] = remove_files(s3, result['filelist_local_etag'], module.params)

            # mark changed if we actually upload something.
            if result.get('uploads') or result.get('removed'):
                result['changed'] = True
            # result.update(filelist=actionable_filelist)
        except botocore.exceptions.ClientError as err:
            error_msg = boto_exception(err)
            module.fail_json(msg=error_msg, exception=traceback.format_exc(), **camel_dict_to_snake_dict(err.response))

    module.exit_json(**result)
Beispiel #27
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(name=dict(required=True),
             image_id=dict(),
             instance_id=dict(),
             key_name=dict(),
             security_groups=dict(default=[], type='list'),
             user_data=dict(),
             user_data_path=dict(type='path'),
             kernel_id=dict(),
             volumes=dict(type='list'),
             instance_type=dict(),
             state=dict(default='present', choices=['present', 'absent']),
             spot_price=dict(type='float'),
             ramdisk_id=dict(),
             instance_profile_name=dict(),
             ebs_optimized=dict(default=False, type='bool'),
             associate_public_ip_address=dict(type='bool',
                                              removed_in_version='2.14'),
             instance_monitoring=dict(default=False, type='bool'),
             assign_public_ip=dict(type='bool'),
             classic_link_vpc_security_groups=dict(type='list'),
             classic_link_vpc_id=dict(),
             vpc_id=dict(),
             placement_tenancy=dict(choices=['default', 'dedicated'])))

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[['user_data',
                                                'user_data_path']])

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(
            module, boto3=True)
        connection = boto3_conn(module,
                                conn_type='client',
                                resource='autoscaling',
                                region=region,
                                endpoint=ec2_url,
                                **aws_connect_kwargs)
    except botocore.exceptions.NoRegionError:
        module.fail_json(msg=(
            "region must be specified as a parameter in AWS_DEFAULT_REGION environment variable or in boto configuration file"
        ))
    except botocore.exceptions.ClientError as e:
        module.fail_json(msg="unable to establish connection - " + str(e),
                         exception=traceback.format_exc(),
                         **camel_dict_to_snake_dict(e.response))

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

    if state == 'present':
        create_launch_config(connection, module)
    elif state == 'absent':
        delete_launch_config(connection, module)
Beispiel #28
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        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=['<=', '<', '>', '>=']),
            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'),
            insufficient_data_actions=dict(type='list'),
            ok_actions=dict(type='list'),
            state=dict(default='present', choices=['present', 'absent']),
        ))

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

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

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

    if region:
        try:
            connection = connect_to_aws(boto.ec2.cloudwatch, region,
                                        **aws_connect_params)
        except (NoAuthHandlerFound, AnsibleAWSError) as e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="region must be specified")

    if state == 'present':
        create_metric_alarm(connection, module)
    elif state == 'absent':
        delete_metric_alarm(connection, module)
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            state=dict(required=False,
                       default='present',
                       choices=['present', 'absent']),
            cluster=dict(required=True, type='str'),
            ec2_instance_id=dict(required=True, type='str'),
            attributes=dict(required=True, type='list'),
        ))

    required_together = [['cluster', 'ec2_instance_id', 'attributes']]

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_together=required_together)

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required.')

    cluster = module.params['cluster']
    ec2_instance_id = module.params['ec2_instance_id']
    attributes = module.params['attributes']

    conti = Ec2EcsInstance(module, cluster, ec2_instance_id)
    attrs = EcsAttributes(module, attributes)

    results = {
        'changed':
        False,
        'attributes': [{
            'cluster': cluster,
            'ec2_instance_id': ec2_instance_id,
            'attributes': attributes
        }]
    }

    attrs_present = conti.attrs_get_by_name(attrs)

    if module.params['state'] == 'present':
        attrs_diff = attrs.diff(attrs_present)
        if not attrs_diff:
            module.exit_json(**results)

        conti.attrs_put(attrs_diff)
        results['changed'] = True

    elif module.params['state'] == 'absent':
        if not attrs_present:
            module.exit_json(**results)

        conti.attrs_delete(attrs_present)
        results['changed'] = True

    module.exit_json(**results)
Beispiel #30
0
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 = ec2_argument_spec()
    argument_spec.update(
        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')

    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)

    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))