コード例 #1
0
def main():
    module_args = dict(
        spec.params('auth', 'tags', 'clear_tags', service='ec2'),
        state=dict(
            type='str',
            choices=['associated', 'allocated', 'absent'],
            default='associated',
        ),
        network_interface=dict(type='str', ),
        instance=dict(type='str', ),
        ip=dict(type='str', ),
    )

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

    try:
        validate_identification_params(module.params)
        ec2 = boto.ec2_resource(module.params['auth'])

        if module.params['state'] == 'associated':
            changed, address = ensure_associated(ec2, module.params,
                                                 module.check_mode)

        elif module.params['state'] == 'allocated':
            changed, address = ensure_allocated(ec2, module.params,
                                                module.check_mode)

        else:
            changed, address = ensure_absent(ec2, module.params,
                                             module.check_mode)

        module.exit_json(changed=changed, object=address)

    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))
コード例 #2
0
ファイル: ec2_vpc.py プロジェクト: andrebellotti/ansible-aws
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            spec.params('auth', 'state', 'id', 'name', 'tags', 'clear_tags'),
            cidr=dict(),
            instance_tenancy=dict(
                # we are not setting a default value to prevent unwanted
                # updates in case the parameter is omitted
                choices=['default', 'dedicated'], ),
        ),
    )

    msg = validate_identification_params(module.params)
    if msg:
        module.fail_json(msg=msg)

    try:
        ec2 = boto.ec2_resource(module.params['auth'])
        changed, vpc, diff = sync(ec2, module.params['state'], module.params,
                                  module.check_mode)
        if vpc is None:
            result = None
        else:
            result = ec2_vpc_utils.result_from_resource(vpc)
    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=changed, diff=diff, object=result)
コード例 #3
0
def main():
    module = AnsibleModule(supports_check_mode=True,
                           argument_spec=dict(vpc=dict(),
                                              **spec.params(
                                                  "names", "ids", "auth",
                                                  "filters")))

    module_filter_mapping = {
        "names": "group-name",
        "ids": "group-id",
        "vpc": "vpc-id"
    }

    secgroups = []
    try:
        ec2 = boto.ec2_resource(module.params['auth'])
        filters = ec2_filters.build_from_mapping(module_filter_mapping,
                                                 module.params)
        secgroups = [
            boto_dict_to_module_return(sg.meta.data)
            for sg in ec2.security_groups.filter(Filters=filters)
        ]
    except errors.AwsCollectionError as e:
        module.fail_json(msg="{0}: {1}".format(type(e), str(e)))
    module.exit_json(changed=False, objects=secgroups)
コード例 #4
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            spec.params('auth', 'ids', 'names', 'filters'),
            vpc=dict(),
        ),
    )

    filter_mapping = dict(
        ec2_filters.mapping_for_params('names'),
        ids='internet-gateway-id',
        vpc='attachment.vpc-id',
    )

    try:
        ec2 = boto.ec2_resource(module.params['auth'])
        filters = ec2_filters.build_from_mapping(filter_mapping, module.params)

        gateways = []
        for gateway in ec2.internet_gateways.filter(Filters=filters):
            gateways.append(
                ec2_internet_gateway_utils.result_from_remote(gateway))

    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e), exception=e)

    module.exit_json(changed=False, objects=gateways)
コード例 #5
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            spec.params('auth', 'availability_zone',
                        'state', 'id', 'name', 'tags', 'clear_tags'),
            vpc=dict(),
            cidr=dict(),
            auto_assign_ip=dict(
                type='bool',
                default=False,
            ),
        ),
    )

    try:
        validate_identification_params(module.params)
        ec2 = boto.ec2_resource(module.params['auth'])

        if module.params['state'] == 'present':
            changed, subnet, diff = handle_present(ec2, module.params, module.check_mode)
        else:
            changed, subnet, diff = handle_absent(ec2, module.params, module.check_mode)

        if subnet is None:
            result = None
        else:
            result = ec2_subnet_utils.result_from_resource(subnet)
    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=changed, object=result, diff=diff)
コード例 #6
0
def main():
    gress_suboptions = dict(
        clear_rules=dict(type="bool", default=False),
        rules=dict(
            type="list",
            elements="dict",
            options=dict(
                protocol=dict(required=True,
                              choices=["all", "tcp", "udp", "icmp", "icmpv6"]),
                port_from=dict(type="int"),
                port_to=dict(type="int"),
                port=dict(type="int"),
                icmp_type=dict(type="int"),
                icmp_code=dict(type="int"),
                security_groups=dict(type="list",
                                     elements="dict",
                                     options=dict(id=dict(required="true"),
                                                  description=dict())),
                ip_ranges=dict(type="list",
                               elements="dict",
                               options=dict(cidr=dict(required="true"),
                                            description=dict()))),
            default=[]))

    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(vpc=dict(),
                           ingress=dict(type="dict",
                                        options=gress_suboptions,
                                        default=dict()),
                           egress=dict(type="dict",
                                       options=gress_suboptions,
                                       default=dict()),
                           **spec.params("auth", "state", "tags", "clear_tags",
                                         "name", "description", "id")),
        required_one_of=[("id", "name")])

    ers = do_custom_validation(module.params)
    if ers:
        module.fail_json(msg="Parameter validation failed: \n    {0}".format(
            "\n    ".join(ers)))

    try:
        ec2 = boto.ec2_resource(module.params["auth"])
        if module.params["state"] == "present":
            changed, result = ensure_present(ec2, module.params,
                                             module.check_mode)
            result = boto_dict_to_module_return(result)
        else:
            changed = ensure_absent(ec2, module.params, module.check_mode)
            result = None
    except errors.AwsCollectionError as e:
        module.fail_json(msg="{0}: {1}".format(type(e), str(e)))
    # noinspection PyUnboundLocalVariable
    module.exit_json(changed=changed, object=result)
コード例 #7
0
def main():
    module_args = dict(
        spec.params('auth', service='ec2'),
        ips=dict(type='list', ),
    )

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

    try:
        ec2 = boto.ec2_resource(module.params['auth'])
        addresses = find_vpc_address(ec2, module.params)
        module.exit_json(changed=False,
                         objects=[create_result(a) for a in addresses])

    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))
コード例 #8
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            spec.params('auth', 'ids', 'names', 'filters'),
            states=dict(
                type='list',
                default=['pending', 'running', 'stopping', 'stopped', 'shutting-down'],
            ),
            ami=dict(),
            type=dict(),
            subnet=dict(),
        ),
    )

    filter_mapping = dict(
        ec2_filters.mapping_for_params('names'),
        ids='instance-id',
        states='instance-state-name',
        ami='image-id',
        type='instance-type',
        subnet='subnet-id',
    )

    try:
        validate_states(module.params['states'])

        ec2 = boto.ec2_resource(module.params['auth'])
        filters = ec2_filters.build_from_mapping(filter_mapping, module.params)

        instances = []
        for instance in ec2.instances.filter(Filters=filters):
            instances.append(
                ec2_instance_utils.result_from_remote(instance)
            )
    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=instances)
コード例 #9
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            subnet=dict(),
            ip=dict(),
            security_groups=dict(type="list"),
            clear_security_groups=dict(type="bool", default=False),
            state=dict(choices=("attached", "detached", "absent"),
                       default="attached"),
            source_dest_check=dict(type="bool"),
            type=dict(choices=("normal", "efa"), default="normal"),
            attachment=dict(
                type="dict",
                options=dict(instance=dict(required=True),
                             device_index=dict(type="int"),
                             keep_on_termination=dict(type="bool")),
            ),
            **spec.params("auth", "id", "tags", "clear_tags", "name",
                          "description")),
        required_if=[("state", "attached", ("attachment", )),
                     ("clear_security_groups", True, ("security_groups", ))])

    try:
        do_custom_validation(module.params)

        ec2 = boto.ec2_resource(module.params["auth"])
        param_entity = NetworkInterface.from_module_params(module.params)

        if module.params["state"] in ("attached", "detached"):
            changed, diff, result = ensure_present(ec2, param_entity,
                                                   module.check_mode)
        else:
            changed, diff = ensure_absent(ec2, param_entity, module.check_mode)
            result = None
    except errors.AwsCollectionError as e:
        module.fail_json(msg="{0}: {1}".format(e.__class__.__name__, str(e)))
    # noinspection PyUnboundLocalVariable
    module.exit_json(changed=changed, object=result, diff=diff)
コード例 #10
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(spec.params('auth', 'ids', 'names', 'filters'), ),
    )

    filter_mapping = dict(
        ec2_filters.mapping_for_params('names'),
        ids='vpc-id',
    )

    try:
        ec2 = boto.ec2_resource(module.params['auth'])
        filters = ec2_filters.build_from_mapping(filter_mapping, module.params)
        vpcs = [
            ec2_vpc_utils.result_from_resource(vpc)
            for vpc in ec2.vpcs.filter(Filters=filters)
        ]
    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=vpcs)
コード例 #11
0
def main():
    required_one_of = [
        ('id', 'name'),
    ]
    required_if = [
        ('state', 'attached', ['vpc']),
    ]

    module = AnsibleModule(
        supports_check_mode=True,
        required_if=required_if,
        required_one_of=required_one_of,
        argument_spec=dict(
            spec.params('auth', 'id', 'name', 'tags', 'clear_tags'),
            state=dict(
                choices=['attached', 'detached', 'absent'],
                default='attached',
            ),
            vpc=dict(),
        ),
    )

    try:
        ec2 = boto.ec2_resource(module.params['auth'])

        # what is typically present state encapsulates two states
        # in our case - attached and detached
        if module.params['state'] in ('attached', 'detached'):
            changed, gateway, diff = handle_present(ec2, module.params,
                                                    module.check_mode)
        else:
            changed, gateway, diff = handle_absent(ec2, module.params,
                                                   module.check_mode)
    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=changed, object=gateway, diff=diff)
コード例 #12
0
def main():
    module = AnsibleModule(supports_check_mode=True,
                           argument_spec=dict(subnet=dict(),
                                              **spec.params(
                                                  "names", "ids", "auth",
                                                  "filters")))

    module_filter_mapping = dict(ec2_filters.mapping_for_params("names"),
                                 ids="network-interface-id",
                                 subnet="subnet-id")

    result = []
    try:
        ec2 = boto.ec2_resource(module.params["auth"])
        filters = ec2_filters.build_from_mapping(module_filter_mapping,
                                                 module.params)
        response = ec2.network_interfaces.filter(Filters=filters)
        entities_sorted = sorted([
            NetworkInterface.from_boto_dict(eni.meta.data) for eni in response
        ])
        result = [eni.to_module_return() for eni in entities_sorted]
    except errors.AwsCollectionError as e:
        module.fail_json(msg="{0}: {1}".format(type(e), str(e)))
    module.exit_json(changed=False, objects=result)
コード例 #13
0
def main():
    mutually_exclusive = [
        # Making network_interface, subnet and availability_zone mutually exclusive
        # prevents user errors due to resource placement (for instance ENI not being
        # in the same AZ/subnet as pointed to by the values of these parameters).
        # This is because:
        #  if network_interface is:
        #    a) provided, the network_interface (implies) -> subnet (implies) -> availability_zone
        #    b) omitted, the primary ENI will be autogenerated in the subnet as follows:
        #       if subnet is:
        #         b1) provided, subnet (implies) -> availability_zone
        #         b2) omitted, we require availability_zone, and retrieve the default
        #             subnet for that availability zone.
        ['network_interface', 'subnet', 'availability_zone'],
        # We have two options:
        #  a) set network_interface and point it to an existing ENI. In this case,
        #     the referenced ENI already has its own security groups configured
        #     and we don't permit manipulating them here (ec2_network_interface should be used).
        #  b) if we omit network_interface we may optionally set security_groups, to
        #     configure the new ENI.
        ['network_interface', 'security_groups'],
    ]

    module = AnsibleModule(
        supports_check_mode=True,
        mutually_exclusive=mutually_exclusive,
        argument_spec=dict(
            spec.params('state', 'availability_zone', 'auth', 'name', 'tags',
                        'clear_tags', 'id'),
            wait_state=dict(
                type='bool',
                default=True,
            ),
            type=dict(),
            ami=dict(),
            key_pair=dict(),
            subnet=dict(),
            network_interface=dict(),
            security_groups=dict(type='list', ),
            monitoring=dict(
                choices=['basic', 'detailed'],
                default='basic',
            ),
            on_instance_initiated_shutdown=dict(
                choices=['stop', 'terminate'],
                default='stop',
            ),
            tenancy=dict(choices=['default', 'dedicated'], ),
        ),
    )

    try:
        ec2 = boto.ec2_resource(module.params['auth'])
        if module.params["state"] == "absent":
            result = None
            changed, diff = ensure_absent(ec2, module.params,
                                          module.check_mode)
        else:
            changed, result, diff = ensure_present(ec2, module.params,
                                                   module.check_mode)

        module.exit_json(changed=changed, object=result, diff=diff)
    except errors.AwsCollectionError as e:
        module.fail_json(msg=str(e))