Beispiel #1
0
    def run_job(self):
        self.status = SUCCESS
        self.log_callback.info('Creating image.')

        self.request_credentials([self.account])
        credentials = self.credentials[self.account]

        config = {
            'user': self.oci_user_id,
            'key_content': credentials['signing_key'],
            'fingerprint': credentials['fingerprint'],
            'tenancy': self.tenancy,
            'region': self.region
        }
        compute_client = ComputeClient(config)
        compute_composite_client = ComputeClientCompositeOperations(
            compute_client)

        object_name = self.status_msg['object_name']
        namespace = self.status_msg['namespace']
        self.cloud_image_name = self.status_msg['cloud_image_name']

        image_source_details = ImageSourceViaObjectStorageTupleDetails(
            bucket_name=self.bucket,
            namespace_name=namespace,
            object_name=object_name,
            source_image_type=self.image_type,
            operating_system=self.operating_system,
            operating_system_version=self.operating_system_version)

        image_details = CreateImageDetails(
            compartment_id=self.compartment_id,
            display_name=self.cloud_image_name,
            image_source_details=image_source_details,
            launch_mode=self.launch_mode)

        retry_strategy = RetryStrategyBuilder(
            max_attempts=self.max_oci_attempts,
            service_error_retry_config={
                'service_error_retry_config': {
                    400: ['LimitExceeded']
                }
            }).get_retry_strategy()
        response = compute_composite_client.create_image_and_wait_for_state(
            create_image_details=image_details,
            wait_for_states=[Image.LIFECYCLE_STATE_AVAILABLE],
            operation_kwargs={'retry_strategy': retry_strategy},
            waiter_kwargs={'max_wait_seconds': self.max_oci_wait_seconds})

        self.status_msg['image_id'] = response.data.id
        self.log_callback.info(
            'Created image has ID: {0}.'.format(object_name))
def _get_create_image_details(module):
    comp_id = module.params["compartment_id"]
    name = module.params["name"]
    instance_id = module.params["instance_id"]
    image_source_details = module.params["image_source_details"]
    launch_mode = module.params["launch_mode"]

    cid = CreateImageDetails()
    cid.compartment_id = comp_id
    cid.display_name = name
    cid.launch_mode = launch_mode
    oci_utils.add_tags_to_model_from_module(cid, module)

    # An image can be created from an instance, or imported from an exported image available in object storage
    if instance_id:
        cid.instance_id = instance_id
    elif image_source_details:
        source_type = image_source_details["source_type"]
        isd = None
        # The exported image can be provided as a tuple(namespace,bucket,object) or a URI
        if source_type == "objectStorageTuple":
            isd = ImageSourceViaObjectStorageTupleDetails()
            isd.source_type = source_type
            isd.namespace_name = image_source_details["namespace"]
            isd.bucket_name = image_source_details["bucket"]
            isd.object_name = image_source_details["object"]
            isd.source_image_type = image_source_details["source_image_type"]
        elif source_type == "objectStorageUri":
            isd = ImageSourceViaObjectStorageUriDetails()
            isd.source_type = source_type
            isd.source_uri = image_source_details["source_uri"]
            isd.source_image_type = image_source_details["source_image_type"]
        cid.image_source_details = isd
    else:
        module.fail_json(
            msg=
            "Specify instance_id or image_source_id while creating an instance."
        )

    return cid
Beispiel #3
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"],
            ),
            launch_mode=dict(
                type="str",
                required=False,
                choices=["NATIVE", "EMULATED", "PARAVIRTUALIZED", "CUSTOM"],
            ),
        )
    )

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

    compute_client = oci_utils.create_service_client(module, ComputeClient)
    state = module.params["state"]

    result = dict(changed=False)

    id = module.params.get("image_id", None)
    exclude_attributes = {"display_name": 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)
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)