#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017-2026 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** Type: MMv1 *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # ---------------------------------------------------------------------------- # from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = r""" --- author: - Google Inc. (@googlecloudplatform) description: - A representation of a collection of database items organized in a way that allows for approximate nearest neighbor (a.k.a ANN) algorithms search. extends_documentation_fragment: - google.cloud.gcp module: gcp_vertexai_index notes: - 'API Reference: U(https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.indexes/)' options: description: description: - The description of the Index. type: str display_name: description: - The display name of the Index. - The name can be up to 128 characters long and can consist of any UTF-8 characters. required: true type: str encryption_spec: description: - Customer-managed encryption key spec for an Index. - If set, this Index and all sub-resources of this Index will be secured by this key. suboptions: kms_key_name: description: - The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. - 'Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`.' - The key needs to be in the same region as where the compute resource is created. required: true type: str type: dict index_update_method: default: BATCH_UPDATE description: - The update method to use with this Index. - The value must be the followings. - If not set, BATCH_UPDATE will be used by default. - '* BATCH_UPDATE: user can call indexes.patch with files on Cloud Storage of datapoints to update.' - '* STREAM_UPDATE: user can call indexes.upsertDatapoints/DeleteDatapoints to update the Index and the updates will be applied in corresponding DeployedIndexes in nearly real-time.' type: str labels: description: - The labels with user-defined metadata to organize your Indexes. type: dict metadata: description: - Additional information about the Index. - Although this field is not marked as required in the API specification, it is currently required when creating an Index and must be provided. - Attempts to create an Index without this field will result in an API error. required: true suboptions: config: description: - The configuration of the Matching Engine Index. required: true suboptions: algorithm_config: description: - The configuration with regard to the algorithms used for efficient search. - This field may be required based on your configuration. suboptions: brute_force_config: description: - Configuration options for using brute force search, which simply implements the standard linear search in the database for each query. type: dict tree_ah_config: description: - Configuration options for using the tree-AH algorithm (Shallow tree + Asymmetric Hashing). - 'Please refer to this paper for more details: https://arxiv.org/abs/1908.10396.' suboptions: leaf_node_embedding_count: default: 1000 description: - Number of embeddings on each leaf node. - The default value is 1000 if not set. type: int leaf_nodes_to_search_percent: default: 10 description: - The default percentage of leaf nodes that any query may be searched. - Must be in range 1-100, inclusive. - The default value is 10 (means 10%) if not set. type: int type: dict type: dict approximate_neighbors_count: description: - The default number of neighbors to find via approximate search before exact reordering is performed. - Exact reordering is a procedure where results returned by an approximate search algorithm are reordered via a more expensive distance computation. - Required if tree-AH algorithm is used. type: int dimensions: description: - The number of dimensions of the input vectors. required: true type: int distance_measure_type: default: DOT_PRODUCT_DISTANCE description: - The distance measure used in nearest neighbor search. - 'The value must be one of the followings: * SQUARED_L2_DISTANCE: Euclidean (L_2) Distance * L1_DISTANCE: Manhattan (L_1) Distance * COSINE_DISTANCE: Cosine Distance.' - Defined as 1 - cosine similarity. - '* DOT_PRODUCT_DISTANCE: Dot Product Distance.' - Defined as a negative of the dot product. type: str feature_norm_type: default: NONE description: - Type of normalization to be carried out on each vector. - 'The value must be one of the followings: * UNIT_L2_NORM: Unit L2 normalization type * NONE: No normalization type is specified.' type: str shard_size: description: - Index data is split into equal parts to be processed. - These are called "shards". - The shard size must be specified when creating an index. - 'The value must be one of the followings: * SHARD_SIZE_SMALL: Small (2GB) * SHARD_SIZE_MEDIUM: Medium (20GB) * SHARD_SIZE_LARGE: Large (50GB).' type: str type: dict contents_delta_uri: description: - Allows inserting, updating or deleting the contents of the Matching Engine Index. - The string must be a valid Cloud Storage directory path. - If this field is set when calling IndexService.UpdateIndex, then no other Index field can be also updated as part of the same call. - The expected structure and format of the files this URI points to is described at https://cloud.google.com/vertex-ai/docs/matching-engine/using-matching-engine#input-data-format. type: str is_complete_overwrite: default: false description: - If this field is set together with contentsDeltaUri when calling IndexService.UpdateIndex, then existing content of the Index will be replaced by the data from the contentsDeltaUri. type: bool type: dict region: description: - The region of the index. - eg us-central1. type: str state: choices: - present - absent default: present description: - Whether the resource should exist in GCP. type: str requirements: - python >= 3.8 - requests >= 2.18.4 - google-auth >= 2.25.1 short_description: Creates a GCP VertexAI.Index resource """ # noqa: E501 EXAMPLES = r""" - name: Create Index google.cloud.gcp_vertexai_index: state: present display_name: "{{ resource_name }}" region: us-central1 metadata: contents_delta_uri: "gs://{{ resource_name }}/contents" config: dimensions: 2 approximate_neighbors_count: 150 shard_size: SHARD_SIZE_SMALL distance_measure_type: DOT_PRODUCT_DISTANCE algorithm_config: tree_ah_config: leaf_node_embedding_count: 500 leaf_nodes_to_search_percent: 7 project: "{{ gcp_project }}" auth_kind: "{{ gcp_cred_kind }}" service_account_file: "{{ gcp_cred_file }}" ################################################################################ - name: Create Index with streaming updates google.cloud.gcp_vertexai_index: state: present display_name: "{{ resource_name }}" region: us-central1 metadata: contents_delta_uri: "gs://{{ resource_name }}/contents" config: dimensions: 2 shard_size: SHARD_SIZE_LARGE distance_measure_type: COSINE_DISTANCE feature_norm_type: UNIT_L2_NORM algorithm_config: brute_force_config: {} index_update_method: STREAM_UPDATE project: "{{ gcp_project }}" auth_kind: "{{ gcp_cred_kind }}" service_account_file: "{{ gcp_cred_file }}" """ # noqa: E501 RETURN = r""" changed: description: Whether the resource was changed. returned: always type: bool createTime: description: - The timestamp of when the Index was created in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. returned: success type: str deployedIndexes: contains: deployedIndexId: description: - The ID of the DeployedIndex in the above IndexEndpoint. returned: success type: str indexEndpoint: description: - A resource name of the IndexEndpoint. returned: success type: str description: - The pointers to DeployedIndexes created from this Index. - An Index can be only deleted if all its DeployedIndexes had been undeployed first. elements: dict returned: success type: list etag: description: - Used to perform consistent read-modify-write updates. returned: success type: str indexStats: contains: shardsCount: description: - The number of shards in the Index. returned: success type: int vectorsCount: description: - The number of vectors in the Index. returned: success type: str description: - Stats of the index resource. returned: success type: dict metadataSchemaUri: description: - Points to a YAML file stored on Google Cloud Storage describing additional information about the Index, that is specific to it. - Unset if the Index does not have any additional information. returned: success type: str name: description: - The resource name of the Index. returned: success type: str state: description: The current state of the resource. returned: always type: str updateTime: description: - The timestamp of when the Index was last updated in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. returned: success type: str """ # noqa: E501 ################################################################################ # Imports ################################################################################ from ansible_collections.google.cloud.plugins.module_utils import gcp_utils as gcp import types # BEGIN Custom imports # END Custom imports def build_link(module_params, uri): params = module_params.copy() return ("https://{region}-aiplatform.googleapis.com/v1/" + uri).format(**params) class DeployedIndexes(gcp.Resource): def _response(self): return { "deployedIndexId": self.response.get("deployedIndexId"), "indexEndpoint": self.response.get("indexEndpoint"), } class EncryptionSpec(gcp.Resource): def _request(self): return { "kmsKeyName": self.request.get("kms_key_name"), } def _response(self): return { "kmsKeyName": self.response.get("kmsKeyName"), } class IndexStats(gcp.Resource): def _response(self): return { "shardsCount": self.response.get("shardsCount"), "vectorsCount": self.response.get("vectorsCount"), } class Metadata(gcp.Resource): def _request(self): return { "config": gcp.remove_empties( MetadataConfig(self.request.get("config", {})).to_request() ), # remove empty values "contentsDeltaUri": self.request.get("contents_delta_uri"), "isCompleteOverwrite": self.request.get("is_complete_overwrite"), } def _response(self): return { "config": MetadataConfig().from_response(self.response.get("config", {})), "contentsDeltaUri": self.response.get("contentsDeltaUri"), "isCompleteOverwrite": self.response.get("isCompleteOverwrite"), } class MetadataConfig(gcp.Resource): def _request(self): return { "algorithmConfig": gcp.remove_empties( MetadataConfigAlgorithmConfig(self.request.get("algorithm_config", {})).to_request() ), # remove empty values "approximateNeighborsCount": self.request.get("approximate_neighbors_count"), "dimensions": self.request.get("dimensions"), "distanceMeasureType": self.request.get("distance_measure_type"), "featureNormType": self.request.get("feature_norm_type"), "shardSize": self.request.get("shard_size"), } def _response(self): return { "algorithmConfig": MetadataConfigAlgorithmConfig().from_response(self.response.get("algorithmConfig", {})), "approximateNeighborsCount": self.response.get("approximateNeighborsCount"), "dimensions": self.response.get("dimensions"), "distanceMeasureType": self.response.get("distanceMeasureType"), "featureNormType": self.response.get("featureNormType"), "shardSize": self.response.get("shardSize"), } class MetadataConfigAlgorithmConfig(gcp.Resource): def _request(self): return { "bruteForceConfig": gcp.remove_nones( MetadataConfigAlgorithmConfigBruteForceConfig(self.request.get("brute_force_config", {})).to_request() ), # allow empty values "treeAhConfig": gcp.remove_empties( MetadataConfigAlgorithmConfigTreeAhConfig(self.request.get("tree_ah_config", {})).to_request() ), # remove empty values } def _response(self): return { "bruteForceConfig": MetadataConfigAlgorithmConfigBruteForceConfig().from_response( self.response.get("bruteForceConfig", {}) ), "treeAhConfig": MetadataConfigAlgorithmConfigTreeAhConfig().from_response( self.response.get("treeAhConfig", {}) ), } class MetadataConfigAlgorithmConfigBruteForceConfig(gcp.Resource): def _request(self): return self.request.get("brute_force_config", dict()) def _response(self): return self.response.get("brute_force_config", dict()) class MetadataConfigAlgorithmConfigTreeAhConfig(gcp.Resource): def _request(self): return { "leafNodeEmbeddingCount": self.request.get("leaf_node_embedding_count"), "leafNodesToSearchPercent": self.request.get("leaf_nodes_to_search_percent"), } def _response(self): return { "leafNodeEmbeddingCount": self.response.get("leafNodeEmbeddingCount"), "leafNodesToSearchPercent": self.response.get("leafNodesToSearchPercent"), } class VertexAI(gcp.Resource): def _request(self): return { "description": self.request.get("description"), "displayName": self.request.get("display_name"), "encryptionSpec": gcp.remove_empties( EncryptionSpec(self.request.get("encryption_spec", {})).to_request() ), # remove empty values "indexUpdateMethod": self.request.get("index_update_method"), "labels": self.request.get("labels"), "metadata": gcp.remove_empties( Metadata(self.request.get("metadata", {})).to_request() ), # remove empty values } def _response(self): return { "createTime": self.response.get("createTime"), "deployedIndexes": [ DeployedIndexes().from_response(item) for item in (self.response.get("deployedIndexes") or []) ], "description": self.response.get("description"), "displayName": self.response.get("displayName"), "encryptionSpec": EncryptionSpec().from_response(self.response.get("encryptionSpec", {})), "etag": self.response.get("etag"), "indexStats": IndexStats().from_response(self.response.get("indexStats", {})), "indexUpdateMethod": self.response.get("indexUpdateMethod"), "labels": self.response.get("labels"), "metadata": Metadata().from_response(self.response.get("metadata", {})), "metadataSchemaUri": self.response.get("metadataSchemaUri"), "name": self.response.get("name"), "updateTime": self.response.get("updateTime"), } ################################################################################ # Main ################################################################################ def encode(self, obj): """ This is a function bound to the main resource object. Its input is the object returned from to_request() and it mutates it before it is sent to the API. """ return obj def decode(self, obj): """ This is a function bound to the main resource object. Its input is the object returned from from_response() and it mutates it before it is returned to the module caller. """ return obj def main(): """Main function""" module = gcp.Module( argument_spec=dict( state=dict( type="str", default="present", choices=["present", "absent"], ), description=dict( type="str", ), display_name=dict( type="str", required=True, ), encryption_spec=dict( type="dict", options=dict( kms_key_name=dict( type="str", required=True, no_log=False, ) ), ), index_update_method=dict( type="str", default="BATCH_UPDATE", ), labels=dict( type="dict", ), metadata=dict( type="dict", required=True, options=dict( config=dict( type="dict", required=True, options=dict( algorithm_config=dict( type="dict", options=dict( brute_force_config=dict( type="dict", ), tree_ah_config=dict( type="dict", options=dict( leaf_node_embedding_count=dict( type="int", default=1000, ), leaf_nodes_to_search_percent=dict( type="int", default=10, ), ), ), ), mutually_exclusive=[["brute_force_config", "tree_ah_config"]], required_one_of=[["brute_force_config", "tree_ah_config"]], ), approximate_neighbors_count=dict( type="int", ), dimensions=dict( type="int", required=True, ), distance_measure_type=dict( type="str", default="DOT_PRODUCT_DISTANCE", ), feature_norm_type=dict( type="str", default="NONE", ), shard_size=dict( type="str", ), ), ), contents_delta_uri=dict( type="str", ), is_complete_overwrite=dict( type="bool", default=False, ), ), ), region=dict( type="str", ), ) ) if not module.params["scopes"]: module.params["scopes"] = ["https://www.googleapis.com/auth/cloud-platform"] state = module.params["state"] changed = False op_configs = gcp.ResourceOpConfigs( { "base_url": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{region}/indexes", "async_uri": "", "verb": "GET", "timeout_minutes": 0, } ), "create": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{region}/indexes", "async_uri": "{op_id}", "verb": "POST", "timeout_minutes": 180, } ), "delete": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{region}/indexes/{name}", "async_uri": "{op_id}", "verb": "DELETE", "timeout_minutes": 180, } ), "read": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{region}/indexes/{name}", "async_uri": "", "verb": "GET", "timeout_minutes": 0, } ), "update": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{region}/indexes/{name}", "async_uri": "{op_id}", "verb": "PATCH", "timeout_minutes": 180, } ), } ) params = gcp.remove_nones(module.params) resource = VertexAI(params, module=module, product="VertexAI", kind="vertexai#index") read_uri = op_configs.read.uri resource._state = state # store the state in the resource object # Bind the encode and decode functions to the resource object resource.encode_func = types.MethodType(encode, resource) resource.decode_func = types.MethodType(decode, resource) custom_diff = None # Set this variable if you want to implement custom diff logic # --------- BEGIN pre-read custom code --------- # for this module, we're hitting the list endpoint and filtering on display name read_uri = op_configs.base_url.uri + "?filter=displayName=" + params.get("display_name") # --------- END pre-read custom code --------- read_url = build_link(params, read_uri) existing_obj = resource.get(read_url, allow_not_found=True) or {} new_obj = {} gcp.debug(module, existing=existing_obj, post=False) # --------- BEGIN post-read custom code --------- # if there are existing indexes, the call would have returned a list if not gcp.empty(existing_obj): for idx in existing_obj.get("indexes", []): if idx.get("displayName") == params.get("display_name"): existing_obj = idx break # --------- END post-read custom code --------- if custom_diff is not None: is_different = custom_diff else: is_different = resource.diff(gcp.remove_empties(existing_obj)) gcp.debug( module, request=gcp.remove_empties(resource.to_request()), existing=existing_obj, post=True, is_different=is_different, ) if gcp.empty(existing_obj): if state == "present": create_uri = op_configs.create.uri create_async_uri = op_configs.create.async_uri try: # --------- BEGIN create code --------- is_async = create_async_uri != "" create_link = build_link(params, create_uri) create_retries = op_configs.create.timeout create_func = getattr(resource, op_configs.create.verb) async_create_func = getattr(resource, op_configs.create.verb + "_async") async_create_link = build_link(params, "") + create_async_uri gcp.debug( module, msg="Creating resource", create_link=create_link, async_create_link=async_create_link, is_async=is_async, ) if is_async: new_obj = async_create_func(create_link, async_link=async_create_link, retries=create_retries) else: new_obj = create_func(create_link) gcp.debug(module, new=new_obj, action="create", post=False) gcp.debug(module, new=new_obj, action="create", post=True) # --------- END create code --------- except Exception as e: module.fail_json(msg=str(e)) changed = True else: pass # nothing to do else: if state == "absent": delete_uri = op_configs.delete.uri delete_async_uri = op_configs.delete.async_uri try: # --------- BEGIN delete code --------- # --------- BEGIN pre-delete custom code --------- # need to set to the required parameter "name" to the existing resource name params["name"] = existing_obj["name"].split("/")[-1] # --------- END pre-delete custom code --------- is_async = delete_async_uri != "" delete_link = build_link(params, delete_uri) delete_retries = op_configs.delete.timeout delete_func = getattr(resource, op_configs.delete.verb) async_delete_func = getattr(resource, op_configs.delete.verb + "_async") async_delete_link = build_link(params, "") + delete_async_uri gcp.debug( module, msg="Destroying resource", delete_link=delete_link, async_delete_link=async_delete_link, is_async=is_async, ) if is_async: new_obj = async_delete_func(delete_link, async_link=async_delete_link, retries=delete_retries) else: new_obj = delete_func(delete_link) # --------- END delete code --------- except Exception as e: module.fail_json(msg=str(e)) changed = True else: if is_different: update_uri = op_configs.update.uri update_async_uri = op_configs.update.async_uri try: # --------- BEGIN update code --------- # --------- BEGIN pre-update custom code --------- # need to set to the required parameter "name" to the existing resource name params["name"] = existing_obj["name"].split("/")[-1] update_mask = [] metadata_mask = [] req_metadata = gcp.remove_empties(resource.to_request().get("metadata")) obj_metadata = gcp.remove_empties(existing_obj.get("metadata")) gcp.debug(module, req_metadata=req_metadata, obj_metadata=obj_metadata) if req_metadata.get("contentsDeltaUri") != obj_metadata.get("contentsDeltaUri"): metadata_mask.append("metadata.contentsDeltaUri") if req_metadata.get("isCompleteOverwrite", False) != obj_metadata.get("isCompleteOverwrite", False): metadata_mask.append("metadata.isCompleteOverwrite") if not gcp.deep_equal(req_metadata["config"], obj_metadata["config"]): metadata_mask.append("metadata.config") # if description is set, we need to update it if "description" in params: update_mask.append("description") if "labels" in params: update_mask.append("labels") # if we're updating metadata, we can't update other fields if len(metadata_mask) > 0 and len(update_mask) > 0: module.fail_json(msg="Cannot update index metadata and other fields at the same time") update_mask.extend(metadata_mask) update_uri += "?updateMask=" + ",".join(update_mask) # --------- END pre-update custom code --------- is_async = update_async_uri != "" update_link = build_link(params, update_uri) update_retries = op_configs.update.timeout update_func = getattr(resource, op_configs.update.verb) async_update_func = getattr(resource, op_configs.update.verb + "_async") async_update_link = build_link(params, "") + update_async_uri gcp.debug( module, msg="Updating resource", update_link=update_link, async_update_link=async_update_link, is_async=is_async, ) if is_async: new_obj = async_update_func(update_link, async_link=async_update_link, retries=update_retries) else: new_obj = update_func(update_link) gcp.debug(module, new=new_obj, action="update", post=False) gcp.debug(module, new=new_obj, action="update", post=True) # --------- END update code --------- except Exception as e: module.fail_json(msg=str(e)) changed = True else: new_obj = existing_obj new_obj.update({"changed": changed}) module.exit_json(**new_obj) if __name__ == "__main__": main()