fix: correct gcp_compute_instance_info filter docs

The link for filter documentation was pointing to
gcloud, which isn't correct as gcp_compute_instance_info
communicates with the API.

fixes #549
This commit is contained in:
Yusuke Tsutsumi 2023-02-18 18:58:31 +00:00 committed by Yusuke Tsutsumi
parent 252f215f2c
commit 12438f9bfb
2 changed files with 50 additions and 23 deletions

View file

@ -0,0 +1,5 @@
# https://github.com/ansible-community/antsibull-changelog/blob/main/docs/changelogs.rst#changelog-fragment-categories
bugfixes:
- >
gcp_compute_instance_info: fix incorrect documentation for filter which incorrectly
pointed to the gcloud filter logic rather than the API (fixes #549)

View file

@ -25,9 +25,13 @@ __metaclass__ = type
# Documentation # Documentation
################################################################################ ################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = ''' DOCUMENTATION = """
--- ---
module: gcp_compute_instance_info module: gcp_compute_instance_info
description: description:
@ -41,7 +45,7 @@ requirements:
options: options:
filters: filters:
description: description:
- A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters). - A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/compute/docs/reference/rest/v1/instances/list)
- Each additional filter in the list will act be added as an AND condition (filter1 - Each additional filter in the list will act be added as an AND condition (filter1
and filter2) . and filter2) .
type: list type: list
@ -100,9 +104,9 @@ notes:
- For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable.
- Environment variables values will only be used if the playbook values are not set. - Environment variables values will only be used if the playbook values are not set.
- The I(service_account_email) and I(service_account_file) options are mutually exclusive. - The I(service_account_email) and I(service_account_file) options are mutually exclusive.
''' """
EXAMPLES = ''' EXAMPLES = """
- name: get info on an instance - name: get info on an instance
gcp_compute_instance_info: gcp_compute_instance_info:
zone: us-central1-a zone: us-central1-a
@ -111,9 +115,9 @@ EXAMPLES = '''
project: test_project project: test_project
auth_kind: serviceaccount auth_kind: serviceaccount
service_account_file: "/tmp/auth.pem" service_account_file: "/tmp/auth.pem"
''' """
RETURN = ''' RETURN = """
resources: resources:
description: List of resources description: List of resources
returned: always returned: always
@ -588,12 +592,17 @@ resources:
- A reference to the zone where the machine resides. - A reference to the zone where the machine resides.
returned: success returned: success
type: str type: str
''' """
################################################################################ ################################################################################
# Imports # Imports
################################################################################ ################################################################################
from ansible_collections.google.cloud.plugins.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest from ansible_collections.google.cloud.plugins.module_utils.gcp_utils import (
navigate_hash,
GcpSession,
GcpModule,
GcpRequest,
)
import json import json
################################################################################ ################################################################################
@ -602,27 +611,40 @@ import json
def main(): def main():
module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), zone=dict(required=True, type='str'))) module = GcpModule(
argument_spec=dict(
filters=dict(type="list", elements="str"),
zone=dict(required=True, type="str"),
)
)
if not module.params['scopes']: if not module.params["scopes"]:
module.params['scopes'] = ['https://www.googleapis.com/auth/compute'] module.params["scopes"] = ["https://www.googleapis.com/auth/compute"]
return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))} return_value = {
"resources": fetch_list(
module, collection(module), query_options(module.params["filters"])
)
}
module.exit_json(**return_value) module.exit_json(**return_value)
def collection(module): def collection(module):
return "https://compute.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances".format(**module.params) return "https://compute.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances".format(
**module.params
)
def fetch_list(module, link, query): def fetch_list(module, link, query):
auth = GcpSession(module, 'compute') auth = GcpSession(module, "compute")
return auth.list(link, return_if_object, array_name='items', params={'filter': query}) return auth.list(
link, return_if_object, array_name="items", params={"filter": query}
)
def query_options(filters): def query_options(filters):
if not filters: if not filters:
return '' return ""
if len(filters) == 1: if len(filters) == 1:
return filters[0] return filters[0]
@ -630,12 +652,12 @@ def query_options(filters):
queries = [] queries = []
for f in filters: for f in filters:
# For multiple queries, all queries should have () # For multiple queries, all queries should have ()
if f[0] != '(' and f[-1] != ')': if f[0] != "(" and f[-1] != ")":
queries.append("(%s)" % ''.join(f)) queries.append("(%s)" % "".join(f))
else: else:
queries.append(f) queries.append(f)
return ' '.join(queries) return " ".join(queries)
def return_if_object(module, response): def return_if_object(module, response):
@ -650,11 +672,11 @@ def return_if_object(module, response):
try: try:
module.raise_for_status(response) module.raise_for_status(response)
result = response.json() result = response.json()
except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: except getattr(json.decoder, "JSONDecodeError", ValueError) as inst:
module.fail_json(msg="Invalid JSON response with error: %s" % inst) module.fail_json(msg="Invalid JSON response with error: %s" % inst)
if navigate_hash(result, ['error', 'errors']): if navigate_hash(result, ["error", "errors"]):
module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) module.fail_json(msg=navigate_hash(result, ["error", "errors"]))
return result return result