Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions plugins/module_utils/gcp_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,47 @@ def get(self, link: str, allow_not_found: bool = True) -> T.Optional[NestedDict]

return self.if_object(self.session().get(link), allow_not_found)

def list(self, link: str, key: str, filters: T.Optional[T.List[str]] = None) -> T.List[NestedDict]:
"""
Lists resources from a GCP API list endpoint, handling pagination automatically.
I chose not to use GcpSession.list() method because the callback signature makes
it hard to adjust to a class method.

Args:
link: The full URL of the list endpoint to call.
key: The JSON response key whose value contains the list of resources
(e.g. "clusters", "instances").
filters: Optional list of filter expressions to narrow results. Each entry
is a filter string following AIP-160 syntax. Multiple entries are
joined with AND - this is the only logical operator applied
automatically; for OR or NOT, include them explicitly within a
single filter entry. String and enum values must be double-quoted
(e.g. 'some_key = "STRING_VALUE"'). See https://google.aip.dev/160.

Returns:
A flat list of resource dicts across all pages.
"""
self.debug(method="list", link=link, filters=filters)
params: T.Dict[str, T.Any] = {}
if filters:
params["filter"] = " AND ".join(filters)

items: T.List[NestedDict] = []
next_page_token: T.Optional[str] = "" # non-None to enter the loop

while next_page_token is not None:
self.debug(next_page_token=next_page_token, link=link, params=params)
response: T.Optional[RequestsResponse] = self.session().full_get(link, params=params or None)
result: T.Optional[NestedDict] = self.if_object(response, allow_not_found=True)
if result is None:
break
items.extend(result.get(key) or [])
next_page_token = result.get("nextPageToken")
if next_page_token:
params["pageToken"] = next_page_token

return items

def wait_for_op(self, op_url: str, retries: int) -> T.Optional[NestedDict]:
"Retry the given number of times for an async operation to succeed"

Expand Down
315 changes: 315 additions & 0 deletions plugins/modules/gcp_alloydb_backup_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,315 @@
#!/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:
- An AlloyDB Backup.
extends_documentation_fragment:
- google.cloud.gcp
module: gcp_alloydb_backup_info
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:
filters:
description:
- A list of filter expression strings used to filter the resources returned by the API.
- Each string is a filter expression (e.g. C(some_field = "SOME_VALUE")).
- Multiple expressions are combined with a logical AND.
- Refer to the filter topic documentation U(https://cloud.google.com/sdk/gcloud/reference/topic/filters).
- Refer to the IAP-160 filter syntax documentation U(https://google.aip.dev/160).
elements: str
type: list
location:
description:
- The location where the alloydb backup should reside.
required: true
type: str
requirements:
- python >= 3.8
- requests >= 2.18.4
- google-auth >= 2.25.1
short_description: List GCP alloydb.Backup resources
""" # noqa: E501

EXAMPLES = r"""
- name: List all gcp_alloydb_backup_info resources
google.cloud.gcp_alloydb_backup_info:
project: "{{ gcp_project }}"
auth_kind: "{{ gcp_cred_kind }}"
service_account_file: "{{ gcp_cred_file }}"
register: result

- name: List gcp_alloydb_backup_info resources matching given filters
google.cloud.gcp_alloydb_backup_info:
filters:
- display_name = "my-resource"
project: "{{ gcp_project }}"
auth_kind: "{{ gcp_cred_kind }}"
service_account_file: "{{ gcp_cred_file }}"
register: result""" # noqa: E501

RETURN = r"""
changed:
description: Whether any changes were made (always false for info modules).
returned: always
type: bool
resources:
contains:
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" }.'
- '**Note**: This field is non-authoritative, and will only manage the annotations present in your configuration.'
returned: when set
type: dict
clusterName:
description:
- The full resource name of the backup source cluster (e.g., projects/{project}/locations/{location}/clusters/{clusterId}).
returned: always
type: str
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
description:
description:
- User-provided description of the backup.
returned: when set
type: str
displayName:
description:
- User-settable and human-readable display name for the Backup.
returned: when set
type: str
encryptionConfig:
contains:
kmsKeyName:
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].'
returned: when set
type: str
description:
- EncryptionConfig describes the encryption config of a cluster or a backup that is encrypted with a CMEK (customer-managed encryption key).
returned: when set
type: dict
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
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" }.'
- '**Note**: This field is non-authoritative, and will only manage the labels present in your configuration.'
returned: when set
type: dict
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
type:
description:
- The backup type, which suggests the trigger for the backup.
returned: when set
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
description: List of Alloydb.Backup resources matching the supplied filters. May be empty, contain a single resource, or multiple resources.
elements: dict
returned: always
type: list
""" # noqa: E501

################################################################################
# Imports
################################################################################

from ansible_collections.google.cloud.plugins.module_utils import gcp_v2


################################################################################
# Main
################################################################################


def main():
"""Main function"""

module = gcp_v2.Module(
argument_spec=dict(
filters=dict(
type="list",
elements="str",
),
location=dict(

Check warning on line 280 in plugins/modules/gcp_alloydb_backup_info.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this constructor call with a literal.

See more on https://sonarcloud.io/project/issues?id=ansible-collections_google.cloud&issues=AZ9KRwo2OFFB0Wg3vei2&open=AZ9KRwo2OFFB0Wg3vei2&pullRequest=769
type="str",
required=True,
),
),
supports_check_mode=True,
)

if not module.params["scopes"]:
module.params["scopes"] = ["https://www.googleapis.com/auth/cloud-platform"]

# info modules only require the "collection" url
op_configs = gcp_v2.ResourceOpConfigs(
base_url="https://alloydb.googleapis.com/v1/",
base_uri="projects/{project}/locations/{location}/backups",
configs={},
)

info = gcp_v2.Resource(
module.params, # only need it to build the link
module=module,
product="Alloydb",
kind="alloydb#backup",
op_configs=op_configs,
)

filter_exprs = module.params.get("filters") or []

link = info.build_link("list")
resources = info.list(link, key="backups", filters=filter_exprs)

module.exit_json(changed=False, resources=resources)


if __name__ == "__main__":
main()
Loading