コード例 #1
0
def main():
    my_logger = oci_utils.get_logger("oci_instance")
    set_logger(my_logger)

    module_args = oci_utils.get_taggable_arg_spec(supports_create=True,
                                                  supports_wait=True)
    module_args.update(
        dict(compartment_id=dict(type='str', required=False),
             name=dict(type='str', required=False, aliases=['display_name']),
             image_id=dict(type='str', required=False, aliases=['id']),
             instance_id=dict(type='str', required=False),
             image_source_details=dict(type='dict', required=False),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['present', 'absent'])))

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False,
        mutually_exclusive=['instance_id', 'image_source_details'],
        required_if=[('state', 'absent', ['image_id'])],
    )

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    compute_client = ComputeClient(config)
    state = module.params['state']

    result = dict(changed=False)

    id = module.params.get("image_id", None)
    exclude_attributes = {'display_name': True, 'launch_mode': True}
    debug("Id is " + str(id))
    if id is not None:
        image_resp = _get_image_from_id(compute_client, id, module)

        if state == 'absent':
            debug("Delete " + id + " requested")
            if image_resp.data is not None:
                debug("Deleting " + image_resp.data.id)
                result = delete_image(compute_client, id, module)
            else:
                debug("Image " + id + " already deleted.")
        elif state == 'present':
            display_name = module.params['name']
            current_image = image_resp.data
            attrs_equal = oci_utils.are_attrs_equal(
                current_image, module,
                ["display_name", "freeform_tags", "defined_tags"])
            if not attrs_equal:
                result = update_image(compute_client, id, display_name, module)
    else:
        result = oci_utils.check_and_create_resource(
            resource_type="image",
            create_fn=create_image,
            kwargs_create={
                "compute_client": compute_client,
                "module": module
            },
            list_fn=compute_client.list_images,
            kwargs_list={"compartment_id": module.params['compartment_id']},
            module=module,
            model=CreateImageDetails(),
            exclude_attributes=exclude_attributes)

    module.exit_json(**result)
コード例 #2
0
def main():
    my_logger = oci_utils.get_logger("oci_instance")
    set_logger(my_logger)

    module_args = oci_utils.get_common_arg_spec(supports_wait=True)
    module_args.update(
        dict(display_name=dict(type='str', required=False, aliases=['name']),
             instance_id=dict(type='str', required=False),
             vnic_attachment_id=dict(type='str',
                                     required=False,
                                     aliases=['id']),
             nic_index=dict(type='int', required=False, default=0),
             create_vnic_details=dict(type='dict',
                                      required=False,
                                      aliases=['vnic']),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['present', 'absent'])))

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False,
        mutually_exclusive=['id', 'create_vnic_details'],
        required_if=[('state', 'absent', ['vnic_attachment_id'])],
    )

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    compute_client = ComputeClient(config)
    state = module.params['state']

    result = dict(changed=False)

    vna_id = module.params['vnic_attachment_id']
    debug("VNIC attachment Id provided by user is " + str(vna_id))

    try:
        if vna_id is not None:
            vna = oci_utils.get_existing_resource(
                compute_client.get_vnic_attachment,
                module,
                vnic_attachment_id=vna_id)

            if state == 'absent':
                if vna is not None:
                    debug("Deleting " + vna.id)
                    result = oci_utils.delete_and_wait(
                        resource_type=RESOURCE_NAME,
                        client=compute_client,
                        get_fn=compute_client.get_vnic_attachment,
                        kwargs_get={"vnic_attachment_id": vna_id},
                        delete_fn=compute_client.detach_vnic,
                        kwargs_delete={"vnic_attachment_id": vna_id},
                        module=module,
                        wait_applicable=True)
                else:
                    debug("VNIC attachment " + vna_id +
                          " already detached. So returning changed=False.")
            else:
                module.fail_json(
                    "To delete a VNIC attachment, set state=absent")
        else:
            # Create a secondary VNIC and attach it to an instance
            instance_id = module.params.get("instance_id")
            exclude_attributes = {'display_name': True}
            default_attribute_values = {"nic_index": 0}
            compartment_id = compute_client.get_instance(
                instance_id=instance_id).data.compartment_id
            result = oci_utils.check_and_create_resource(
                resource_type=RESOURCE_NAME,
                create_fn=attach_vnic,
                kwargs_create={
                    "compute_client": compute_client,
                    "module": module
                },
                list_fn=compute_client.list_vnic_attachments,
                kwargs_list={
                    "compartment_id": compartment_id,
                    "instance_id": instance_id
                },
                module=module,
                model=AttachVnicDetails(),
                exclude_attributes=exclude_attributes,
                default_attribute_values=default_attribute_values)
    except ServiceError as ex:
        module.fail_json(msg=ex.message)
    except MaximumWaitTimeExceeded as mwte:
        module.fail_json(msg=str(mwte))

    module.exit_json(**result)
コード例 #3
0
def main():
    set_logger(oci_utils.get_logger("oci_swift_password"))

    module_args = oci_utils.get_common_arg_spec(supports_create=True)
    module_args.update(
        dict(user_id=dict(type='str', required=True),
             swift_password_id=dict(type='str',
                                    required=False,
                                    aliases=['id'],
                                    no_log=True),
             description=dict(type='str', required=False),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['present', 'absent'])))

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False,
        required_if=[('state', 'absent', ['swift_password_id'])],
    )

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    identity_client = IdentityClient(config)
    state = module.params['state']

    result = dict(changed=False)

    user_id = module.params.get("user_id", None)
    id = module.params.get("swift_password_id", None)
    description = module.params.get('description', None)
    get_logger().debug("Id is " + str(id))

    if id is not None:
        sw_pass = _get_swift_password_from_id(identity_client, user_id, id,
                                              module)

        if state == 'absent':
            get_logger().debug(
                "Delete swift password %s for user %s requested", id, user_id)
            if sw_pass:
                get_logger().debug("Deleting %s", sw_pass.id)
                result = delete_swift_password(identity_client, user_id, id,
                                               module)
            else:
                get_logger().debug("Swift Password %s already deleted.", id)
        elif state == 'present':
            if sw_pass.description != description:
                result = update_swift_password(identity_client, user_id, id,
                                               description, module)
            else:
                # No change needed, return existing swift password details
                result[RESOURCE_NAME] = to_dict(sw_pass)
    else:
        # Check and create swift password if necessary
        result = oci_utils.check_and_create_resource(
            resource_type=RESOURCE_NAME,
            create_fn=create_swift_password,
            kwargs_create={
                "identity_client": identity_client,
                "user_id": user_id,
                "description": description,
                "module": module
            },
            list_fn=identity_client.list_swift_passwords,
            kwargs_list={"user_id": user_id},
            module=module,
            model=CreateSwiftPasswordDetails())

    module.exit_json(**result)
コード例 #4
0
def main():
    module_args = oci_utils.get_common_arg_spec()
    module_args.update(
        dict(public_ip_id=dict(type='str', required=False, aliases=['id']),
             private_ip_id=dict(type='str', required=False),
             ip_address=dict(type='str', required=False),
             scope=dict(type='str',
                        required=False,
                        choices=["REGION", "AVAILABILITY_DOMAIN"]),
             compartment_id=dict(type='str', required=False),
             availability_domain=dict(type='str', required=False)))

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

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    virtual_network_client = VirtualNetworkClient(config)

    public_ip_id = module.params['public_ip_id']

    try:
        if public_ip_id is not None:
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_public_ip,
                        public_ip_id=public_ip_id).data)
            ]
        elif module.params['private_ip_id'] is not None:
            pvt_ip_id_details = GetPublicIpByPrivateIpIdDetails(
                private_ip_id=module.params['private_ip_id'])
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_public_ip_by_private_ip_id,
                        get_public_ip_by_private_ip_id_details=pvt_ip_id_details
                    ).data)
            ]
        elif module.params['ip_address'] is not None:
            ip_address_details = GetPublicIpByIpAddressDetails(
                ip_address=module.params['ip_address'])
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_public_ip_by_ip_address,
                        get_public_ip_by_ip_address_details=ip_address_details
                    ).data)
            ]
        elif module.params['scope'] is not None:
            list_args = {
                'scope': module.params['scope'],
                'compartment_id': module.params['compartment_id']
            }
            if module.params['availability_domain'] is not None:
                list_args['availability_domain'] = module.params[
                    'availability_domain']

            result = to_dict(
                oci_utils.list_all_resources(
                    virtual_network_client.list_public_ips, **list_args))
        else:
            module.fail_json(
                msg=
                "Specify scope along with compartment_id to list all public IPs or one of"
                "public_ip_id/private_ip_id/ip_address.")
    except ServiceError as ex:
        module.fail_json(msg=ex.message)

    module.exit_json(public_ips=result)
コード例 #5
0
def main():
    module_args = oci_utils.get_taggable_arg_spec(supports_create=True,
                                                  supports_wait=True)
    module_args.update(
        dict(availability_domain=dict(type='str', required=False),
             compartment_id=dict(type='str', required=False),
             volume_id=dict(type='str', required=False, aliases=['id']),
             display_name=dict(type='str', required=False, aliases=['name']),
             size_in_gbs=dict(type='int', required=False, default=50),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['absent', 'present']),
             source_details=dict(type='dict', required=False),
             lookup_all_attached_instances=dict(type='bool',
                                                required=False,
                                                default='no')))

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False,
        required_together=[['availability_domain', 'compartment_id']],
        required_if=[['state', 'absent', ['volume_id']]])

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    block_storage_client = BlockstorageClient(config)

    state = module.params['state']
    volume_id = module.params['volume_id']

    if state == 'absent':
        result = handle_delete_volume(block_storage_client, module)

    else:
        if volume_id is None:
            # Exclude size_in_mbs as it is deprecated but still in the CreateVolumeDetails.

            # Though the documentation
            # (https://oracle-cloud-infrastructure-python-sdk.readthedocs.io/en/latest/api/index.html#id194) says
            #  volumes are by default 1 TB but volumes get created with 50 GB size.
            exclude_attributes = {"size_in_mbs": True, "display_name": True}
            default_attribute_values = {
                "source_details": None,
                "size_in_gbs": 50
            }
            result = oci_utils.check_and_create_resource(
                resource_type='volume',
                create_fn=handle_create_volume,
                kwargs_create={
                    'block_storage_client': block_storage_client,
                    'module': module
                },
                list_fn=block_storage_client.list_volumes,
                kwargs_list={
                    'compartment_id': module.params['compartment_id']
                },
                module=module,
                model=CreateVolumeDetails(),
                exclude_attributes=exclude_attributes,
                default_attribute_values=default_attribute_values)

        else:
            result = handle_update_volume(block_storage_client, module)

    add_attached_instance_info(config, module, result,
                               module.params['lookup_all_attached_instances'])

    module.exit_json(**result)
コード例 #6
0
def main():
    module_args = oci_utils.get_taggable_arg_spec(supports_create=True,
                                                  supports_wait=True)
    module_args.update(
        dict(availability_domain=dict(type='str', required=False),
             cidr_block=dict(type='str', required=False),
             compartment_id=dict(type='str', required=False),
             dhcp_options_id=dict(type='str', required=False),
             display_name=dict(type='str', required=False, aliases=['name']),
             dns_label=dict(type='str', required=False),
             prohibit_public_ip_on_vnic=dict(type='bool',
                                             required=False,
                                             default=False),
             route_table_id=dict(type='str', required=False),
             security_list_ids=dict(type='list', required=False),
             subnet_id=dict(type='str', required=False, aliases=['id']),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['absent', 'present']),
             vcn_id=dict(type='str', required=False)))

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

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    virtual_network_client = VirtualNetworkClient(config)
    exclude_attributes = {
        'display_name': True,
        'dns_label': True,
        'dhcp_options_id': True
    }
    state = module.params['state']
    subnet_id = module.params['subnet_id']

    if state == 'absent':
        if subnet_id is not None:
            result = delete_subnet(virtual_network_client, module)
        else:
            module.fail_json(
                msg=
                "Specify subnet_id with state as 'absent' to delete a subnet.")

    else:
        if subnet_id is not None:
            result = update_subnet(virtual_network_client, module)
        else:
            vcn = oci_utils.call_with_backoff(
                virtual_network_client.get_vcn,
                vcn_id=module.params["vcn_id"]).data

            default_attribute_values = {
                "dhcp_options_id": vcn.default_dhcp_options_id,
                "prohibit_public_ip_on_vnic": False,
                "route_table_id": vcn.default_route_table_id,
                "security_list_ids": [vcn.default_security_list_id]
            }

            result = oci_utils.check_and_create_resource(
                resource_type='subnet',
                create_fn=create_subnet,
                kwargs_create={
                    'virtual_network_client': virtual_network_client,
                    'module': module
                },
                list_fn=virtual_network_client.list_subnets,
                kwargs_list={
                    'compartment_id': module.params['compartment_id'],
                    'vcn_id': module.params['vcn_id']
                },
                module=module,
                model=CreateSubnetDetails(),
                exclude_attributes=exclude_attributes,
                default_attribute_values=default_attribute_values)

    module.exit_json(**result)
コード例 #7
0
def main():
    module_args = oci_utils.get_taggable_arg_spec(supports_create=True, supports_wait=True)
    module_args.update(dict(
        compartment_id=dict(type='str', required=False),
        lifetime=dict(type='str', required=False, choices=['EPHEMERAL', 'RESERVED']),
        display_name=dict(type='str', required=False, aliases=['name']),
        state=dict(type='str', required=False, default='present', choices=['absent', 'present']),
        private_ip_id=dict(type='str', required=False),
        public_ip_id=dict(type='str', required=False, aliases=['id'])
    ))

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False,
        required_if=[
            ('state', 'absent', ['public_ip_id']),
            ('lifetime', 'EPHEMERAL', ['private_ip_id'])
        ]
    )

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    virtual_network_client = VirtualNetworkClient(config)

    state = module.params['state']
    public_ip_id = module.params['public_ip_id']

    if state == 'absent':
        result = delete_public_ip(virtual_network_client, module)

    else:
        if public_ip_id is not None:
            result = update_public_ip(virtual_network_client, module)
        else:
            exclude_attributes = {'display_name': True}
            # If the user desired lifetime of the public IP to be created is RESERVED, then use SCOPE as REGION for
            # making a call to list all the public IPs else use SCOPE as AVAILABILITY_DOMAIN.
            if module.params["lifetime"] == "RESERVED":
                kwargs_list = {'scope': "REGION",
                               'compartment_id': module.params['compartment_id']}
            else:
                # To list ephemeral public IPs, availability domain parameter is required. An ephemeral public IP is
                # always in the same Availability Domain as the private IP it's assigned to. Get the AD from private_ip.
                pvt_ip_ad = virtual_network_client.get_private_ip(
                    module.params["private_ip_id"]).data.availability_domain
                kwargs_list = {'scope': "AVAILABILITY_DOMAIN",
                               'compartment_id': module.params['compartment_id'],
                               'availability_domain': pvt_ip_ad}
            result = oci_utils.check_and_create_resource(resource_type='public_ip',
                                                         create_fn=create_public_ip,
                                                         kwargs_create={
                                                             'virtual_network_client': virtual_network_client,
                                                             'module': module},
                                                         list_fn=virtual_network_client.list_public_ips,
                                                         kwargs_list=kwargs_list,
                                                         module=module,
                                                         model=CreatePublicIpDetails(),
                                                         exclude_attributes=exclude_attributes
                                                         )
    module.exit_json(**result)
コード例 #8
0
def main():
    module_args = oci_utils.get_common_arg_spec()
    module_args.update(
        dict(zone_id=dict(type='str', required=False, aliases=['id']),
             name=dict(type='str', required=False, aliases=['zone_name']),
             compartment_id=dict(type='str', required=False),
             zone_type=dict(type='str',
                            required=False,
                            choices=['PRIMARY', 'SECONDARY']),
             name_contains=dict(type='str', required=False),
             time_created_greater_than_or_equal_to=dict(type='str',
                                                        required=False),
             time_created_less_than=dict(type='str', required=False),
             lifecycle_state=dict(type='str', required=False)))

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=False,
                           required_one_of=[['zone_id', 'compartment_id']])

    if not HAS_OCI_PY_SDK:
        module.fail_json(msg='oci python sdk required for this module.')

    config = oci_utils.get_oci_config(module)
    dns_client = DnsClient(config)

    zone_id = module.params['zone_id']
    compartment_id = module.params['compartment_id']

    try:
        if zone_id is not None:
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        dns_client.get_zone,
                        zone_name_or_id=get_zone_name_or_id(module)).data)
            ]
        elif compartment_id is not None:
            optional_list_method_params = [
                'compartment_id', 'name', 'zone_type', 'name_contains',
                'time_created_greater_than_or_equal_to',
                'time_created_less_than', 'lifecycle_state'
            ]
            optional_kwargs = {
                param: module.params[param]
                for param in optional_list_method_params
                if module.params.get(param) is not None
            }
            zone_summaries = to_dict(
                oci_utils.list_all_resources(dns_client.list_zones,
                                             **optional_kwargs))

            # Get Zone model from zone-summaries returned by `list_zones`
            result = to_dict([
                oci_utils.call_with_backoff(dns_client.get_zone,
                                            zone_name_or_id=z['id']).data
                for z in zone_summaries
            ])
    except ServiceError as ex:
        module.fail_json(msg=ex.message)

    module.exit_json(zones=result)