#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017-2025 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: - An AlloyDB Backup. extends_documentation_fragment: - google.cloud.gcp module: gcp_alloydb_backup notes: - 'API Reference: U(https://cloud.google.com/alloydb/docs/reference/rest/v1/projects.locations.backups/create)' - 'AlloyDB Guide: U(https://cloud.google.com/alloydb/docs/)' options: annotations: description: - Annotations to allow client tools to store small amount of arbitrary data. - This is distinct from labels. - 'https://google.aip.dev/128 An object containing a list of "key": value pairs.' - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.' type: dict backup_id: description: - The ID of the alloydb backup. required: true type: str cluster_name: description: - The full resource name of the backup source cluster (e.g., projects/{project}/locations/{location}/clusters/{clusterId}). required: true type: str description: description: - User-provided description of the backup. type: str display_name: description: - User-settable and human-readable display name for the Backup. type: str encryption_config: description: - EncryptionConfig describes the encryption config of a cluster or a backup that is encrypted with a CMEK (customer-managed encryption key). suboptions: kms_key_name: description: - The fully-qualified resource name of the KMS key. - >- Each Cloud KMS key is regionalized and has the following format: projects/[PROJECT]/locations/[REGION]/keyRings/[RING]/cryptoKeys/[KEY_NAME]. type: str type: dict labels: description: - User-defined labels for the alloydb backup. - 'An object containing a list of "key": value pairs.' - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.' type: dict location: description: - The location where the alloydb backup should reside. required: true type: str state: choices: - present - absent default: present description: - Whether the resource should exist in GCP. type: str type: choices: - TYPE_UNSPECIFIED - ON_DEMAND - AUTOMATED - CONTINUOUS description: - The backup type, which suggests the trigger for the backup. type: str requirements: - python >= 3.8 - requests >= 2.18.4 - google-auth >= 2.25.1 short_description: Creates a GCP Alloydb.Backup resource """ EXAMPLES = r""" - name: Create an on-demand backup for a cluster google.cloud.gcp_alloydb_backup: backup_id: my-backup state: present cluster_name: projects/my-project/locations/us-central1/clusters/my-cluster type: ON_DEMAND location: us-central1 """ RETURN = r""" changed: description: Whether the resource was changed. returned: always type: bool clusterUid: description: - Output only. - The system-generated UID of the cluster which was used to create this resource. returned: success type: str createTime: description: - Output only. - Create time stamp. - A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. - 'Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".' returned: success type: str deleteTime: description: - Output only. - Delete time stamp. - A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. - 'Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".' returned: success type: str encryptionInfo: contains: encryptionType: description: - Output only. - Type of encryption. returned: success type: str kmsKeyVersions: description: - Output only. - Cloud KMS key versions that are being used to protect the database or the backup. elements: str returned: success type: list description: - EncryptionInfo describes the encryption information of a cluster or a backup. returned: success type: dict etag: description: - For Resource freshness validation (https://google.aip.dev/154). returned: success type: str expiryQuantity: contains: retentionCount: description: - Output only. - The backup's position among its backups with the same source cluster and type, by descending chronological order create time (i.e. - newest first). returned: success type: int totalRetentionCount: description: - Output only. - The length of the quantity-based queue, specified by the backup's retention policy. returned: success type: int description: - Output only. - The QuantityBasedExpiry of the backup, specified by the backup's retention policy. - Once the expiry quantity is over retention, the backup is eligible to be garbage collected. returned: success type: dict expiryTime: description: - Output only. - The time at which after the backup is eligible to be garbage collected. - It is the duration specified by the backup's retention policy, added to the backup's createTime. returned: success type: str name: description: - Output only. - 'The name of the backup resource with the format: * projects/{project}/locations/{region}/backups/{backupId}.' returned: success type: str reconciling: description: - Output only. - Reconciling (https://google.aip.dev/128#reconciliation), if true, indicates that the service is actively updating the resource. - This can happen due to user-triggered updates or system actions like failover or maintenance. returned: success type: bool sizeBytes: description: - Output only. - The size of the backup in bytes. returned: success type: str state: description: - Output only. - The current state of the backup. returned: success type: str uid: description: - Output only. - The system-generated UID of the resource. - The UID is assigned when the resource is created, and it is retained until it is deleted. returned: success type: str updateTime: description: - Output only. - Update time stamp. - A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. - 'Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".' returned: success type: str """ ################################################################################ # Imports ################################################################################ from ansible_collections.google.cloud.plugins.module_utils import gcp_utils as gcp # BEGIN Custom imports # END Custom imports def build_link(module, uri): params = module.params.copy() return "https://alloydb.googleapis.com/v1/" + uri.format(**params) class EncryptionConfig(gcp.Resource): def _request(self): return { "kmsKeyName": self.request.get("kms_key_name"), } def _response(self): return { "kmsKeyName": self.response.get("kmsKeyName"), } class EncryptionInfo(gcp.Resource): def _response(self): return { "encryptionType": self.response.get("encryptionType"), "kmsKeyVersions": self.response.get("kmsKeyVersions"), } class ExpiryQuantity(gcp.Resource): def _response(self): return { "retentionCount": self.response.get("retentionCount"), "totalRetentionCount": self.response.get("totalRetentionCount"), } class Alloydb(gcp.Resource): def _request(self): return { "annotations": self.request.get("annotations"), "clusterName": self.request.get("cluster_name"), "description": self.request.get("description"), "displayName": self.request.get("display_name"), "encryptionConfig": EncryptionConfig(self.request.get("encryption_config", {})).to_request(), "labels": self.request.get("labels"), "type": self.request.get("type"), } def _response(self): return { "annotations": self.response.get("annotations"), "clusterName": self.response.get("clusterName"), "clusterUid": self.response.get("clusterUid"), "createTime": self.response.get("createTime"), "deleteTime": self.response.get("deleteTime"), "description": self.response.get("description"), "displayName": self.response.get("displayName"), "encryptionConfig": EncryptionConfig().from_response(self.response.get("encryptionConfig", {})), "encryptionInfo": EncryptionInfo().from_response(self.response.get("encryptionInfo", {})), "etag": self.response.get("etag"), "expiryQuantity": ExpiryQuantity().from_response(self.response.get("expiryQuantity", {})), "expiryTime": self.response.get("expiryTime"), "labels": self.response.get("labels"), "name": self.response.get("name"), "reconciling": self.response.get("reconciling"), "sizeBytes": self.response.get("sizeBytes"), "type": self.response.get("type"), "uid": self.response.get("uid"), "updateTime": self.response.get("updateTime"), } ################################################################################ # Main ################################################################################ def main(): """Main function""" module = gcp.Module( argument_spec=dict( state=dict( type="str", default="present", choices=["present", "absent"], ), annotations=dict( type="dict", ), backup_id=dict( type="str", required=True, ), cluster_name=dict( type="str", required=True, ), description=dict( type="str", ), display_name=dict( type="str", ), encryption_config=dict( type="dict", options=dict( kms_key_name=dict( type="str", ) ), ), labels=dict( type="dict", ), location=dict( type="str", required=True, ), type=dict( type="str", choices=["TYPE_UNSPECIFIED", "ON_DEMAND", "AUTOMATED", "CONTINUOUS"], ), ) ) 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( { "create": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{location}/backups?backupId={backup_id}", "async_uri": "{op_id}", "verb": "POST", "timeout_minutes": 10, } ), "delete": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{location}/backups/{backup_id}", "async_uri": "{op_id}", "verb": "DELETE", "timeout_minutes": 10, } ), "read": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{location}/backups/{backup_id}", "async_uri": "", "verb": "GET", "timeout_minutes": 0, } ), "update": gcp.ResourceOpConfig( **{ "uri": "projects/{project}/locations/{location}/backups/{backup_id}", "async_uri": "{op_id}", "verb": "PATCH", "timeout_minutes": 10, } ), } ) params = gcp.remove_nones_from_dict(module.params) resource = Alloydb(params, module=module, product="Alloydb", kind="alloydb#backup") existing_obj = resource.get(build_link(module, op_configs.read.uri), allow_not_found=True) if existing_obj is None: if state == "present": is_async = op_configs.create.async_uri != "" create_link = build_link(module, op_configs.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(module, "") + op_configs.create.async_uri # --------- BEGIN custom pre-create code --------- # --------- END custom pre-create code --------- try: 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) changed = True except Exception as e: module.fail_json(msg=str(e)) else: pass # nothing to do else: if state == "absent": is_async = op_configs.delete.async_uri != "" delete_link = build_link(module, op_configs.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(module, "") + op_configs.delete.async_uri # --------- BEGIN custom pre-delete code --------- # --------- END custom pre-delete code --------- try: 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) changed = True except Exception as e: module.fail_json(msg=str(e)) else: if resource.diff(existing_obj): is_async = op_configs.update.async_uri != "" update_link = build_link(module, op_configs.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(module, "") + op_configs.update.async_uri # --------- BEGIN custom pre-update code --------- # --------- END custom pre-update code --------- try: 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) except Exception as e: module.fail_json(msg=str(e)) changed = resource.diff(new_obj) new_obj = resource.get(build_link(module, op_configs.read.uri), allow_not_found=True) new_obj = resource.from_response(new_obj or {}) new_obj.update({"changed": changed}) module.exit_json(**new_obj) if __name__ == "__main__": main()