1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2017 Google
5# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6# ----------------------------------------------------------------------------
7#
8#     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***
9#
10# ----------------------------------------------------------------------------
11#
12#     This file is automatically generated by Magic Modules and manual
13#     changes will be clobbered when the file is regenerated.
14#
15#     Please read more about how to change this file at
16#     https://www.github.com/GoogleCloudPlatform/magic-modules
17#
18# ----------------------------------------------------------------------------
19
20from __future__ import absolute_import, division, print_function
21
22__metaclass__ = type
23
24################################################################################
25# Documentation
26################################################################################
27
28ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
29
30DOCUMENTATION = '''
31---
32module: gcp_compute_health_check_info
33description:
34- Gather info for GCP HealthCheck
35- This module was called C(gcp_compute_health_check_facts) before Ansible 2.9. The
36  usage has not changed.
37short_description: Gather info for GCP HealthCheck
38version_added: 2.7
39author: Google Inc. (@googlecloudplatform)
40requirements:
41- python >= 2.6
42- requests >= 2.18.4
43- google-auth >= 1.3.0
44options:
45  filters:
46    description:
47    - A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters).
48    - Each additional filter in the list will act be added as an AND condition (filter1
49      and filter2) .
50    type: list
51extends_documentation_fragment: gcp
52'''
53
54EXAMPLES = '''
55- name: get info on a health check
56  gcp_compute_health_check_info:
57    filters:
58    - name = test_object
59    project: test_project
60    auth_kind: serviceaccount
61    service_account_file: "/tmp/auth.pem"
62'''
63
64RETURN = '''
65resources:
66  description: List of resources
67  returned: always
68  type: complex
69  contains:
70    checkIntervalSec:
71      description:
72      - How often (in seconds) to send a health check. The default value is 5 seconds.
73      returned: success
74      type: int
75    creationTimestamp:
76      description:
77      - Creation timestamp in RFC3339 text format.
78      returned: success
79      type: str
80    description:
81      description:
82      - An optional description of this resource. Provide this property when you create
83        the resource.
84      returned: success
85      type: str
86    healthyThreshold:
87      description:
88      - A so-far unhealthy instance will be marked healthy after this many consecutive
89        successes. The default value is 2.
90      returned: success
91      type: int
92    id:
93      description:
94      - The unique identifier for the resource. This identifier is defined by the
95        server.
96      returned: success
97      type: int
98    name:
99      description:
100      - Name of the resource. Provided by the client when the resource is created.
101        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
102        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
103        which means the first character must be a lowercase letter, and all following
104        characters must be a dash, lowercase letter, or digit, except the last character,
105        which cannot be a dash.
106      returned: success
107      type: str
108    timeoutSec:
109      description:
110      - How long (in seconds) to wait before claiming failure.
111      - The default value is 5 seconds. It is invalid for timeoutSec to have greater
112        value than checkIntervalSec.
113      returned: success
114      type: int
115    unhealthyThreshold:
116      description:
117      - A so-far healthy instance will be marked unhealthy after this many consecutive
118        failures. The default value is 2.
119      returned: success
120      type: int
121    type:
122      description:
123      - Specifies the type of the healthCheck, either TCP, SSL, HTTP or HTTPS. If
124        not specified, the default is TCP. Exactly one of the protocol-specific health
125        check field must be specified, which must match type field.
126      returned: success
127      type: str
128    httpHealthCheck:
129      description:
130      - A nested object resource.
131      returned: success
132      type: complex
133      contains:
134        host:
135          description:
136          - The value of the host header in the HTTP health check request.
137          - If left empty (default value), the public IP on behalf of which this health
138            check is performed will be used.
139          returned: success
140          type: str
141        requestPath:
142          description:
143          - The request path of the HTTP health check request.
144          - The default value is /.
145          returned: success
146          type: str
147        response:
148          description:
149          - The bytes to match against the beginning of the response data. If left
150            empty (the default value), any response will indicate health. The response
151            data can only be ASCII.
152          returned: success
153          type: str
154        port:
155          description:
156          - The TCP port number for the HTTP health check request.
157          - The default value is 80.
158          returned: success
159          type: int
160        portName:
161          description:
162          - Port name as defined in InstanceGroup#NamedPort#name. If both port and
163            port_name are defined, port takes precedence.
164          returned: success
165          type: str
166        proxyHeader:
167          description:
168          - Specifies the type of proxy header to append before sending data to the
169            backend, either NONE or PROXY_V1. The default is NONE.
170          returned: success
171          type: str
172        portSpecification:
173          description:
174          - 'Specifies how port is selected for health checking, can be one of the
175            following values: * `USE_FIXED_PORT`: The port number in `port` is used
176            for health checking.'
177          - "* `USE_NAMED_PORT`: The `portName` is used for health checking."
178          - "* `USE_SERVING_PORT`: For NetworkEndpointGroup, the port specified for
179            each network endpoint is used for health checking. For other backends,
180            the port or named port specified in the Backend Service is used for health
181            checking."
182          - If not specified, HTTP health check follows behavior specified in `port`
183            and `portName` fields.
184          returned: success
185          type: str
186    httpsHealthCheck:
187      description:
188      - A nested object resource.
189      returned: success
190      type: complex
191      contains:
192        host:
193          description:
194          - The value of the host header in the HTTPS health check request.
195          - If left empty (default value), the public IP on behalf of which this health
196            check is performed will be used.
197          returned: success
198          type: str
199        requestPath:
200          description:
201          - The request path of the HTTPS health check request.
202          - The default value is /.
203          returned: success
204          type: str
205        response:
206          description:
207          - The bytes to match against the beginning of the response data. If left
208            empty (the default value), any response will indicate health. The response
209            data can only be ASCII.
210          returned: success
211          type: str
212        port:
213          description:
214          - The TCP port number for the HTTPS health check request.
215          - The default value is 443.
216          returned: success
217          type: int
218        portName:
219          description:
220          - Port name as defined in InstanceGroup#NamedPort#name. If both port and
221            port_name are defined, port takes precedence.
222          returned: success
223          type: str
224        proxyHeader:
225          description:
226          - Specifies the type of proxy header to append before sending data to the
227            backend, either NONE or PROXY_V1. The default is NONE.
228          returned: success
229          type: str
230        portSpecification:
231          description:
232          - 'Specifies how port is selected for health checking, can be one of the
233            following values: * `USE_FIXED_PORT`: The port number in `port` is used
234            for health checking.'
235          - "* `USE_NAMED_PORT`: The `portName` is used for health checking."
236          - "* `USE_SERVING_PORT`: For NetworkEndpointGroup, the port specified for
237            each network endpoint is used for health checking. For other backends,
238            the port or named port specified in the Backend Service is used for health
239            checking."
240          - If not specified, HTTPS health check follows behavior specified in `port`
241            and `portName` fields.
242          returned: success
243          type: str
244    tcpHealthCheck:
245      description:
246      - A nested object resource.
247      returned: success
248      type: complex
249      contains:
250        request:
251          description:
252          - The application data to send once the TCP connection has been established
253            (default value is empty). If both request and response are empty, the
254            connection establishment alone will indicate health. The request data
255            can only be ASCII.
256          returned: success
257          type: str
258        response:
259          description:
260          - The bytes to match against the beginning of the response data. If left
261            empty (the default value), any response will indicate health. The response
262            data can only be ASCII.
263          returned: success
264          type: str
265        port:
266          description:
267          - The TCP port number for the TCP health check request.
268          - The default value is 443.
269          returned: success
270          type: int
271        portName:
272          description:
273          - Port name as defined in InstanceGroup#NamedPort#name. If both port and
274            port_name are defined, port takes precedence.
275          returned: success
276          type: str
277        proxyHeader:
278          description:
279          - Specifies the type of proxy header to append before sending data to the
280            backend, either NONE or PROXY_V1. The default is NONE.
281          returned: success
282          type: str
283        portSpecification:
284          description:
285          - 'Specifies how port is selected for health checking, can be one of the
286            following values: * `USE_FIXED_PORT`: The port number in `port` is used
287            for health checking.'
288          - "* `USE_NAMED_PORT`: The `portName` is used for health checking."
289          - "* `USE_SERVING_PORT`: For NetworkEndpointGroup, the port specified for
290            each network endpoint is used for health checking. For other backends,
291            the port or named port specified in the Backend Service is used for health
292            checking."
293          - If not specified, TCP health check follows behavior specified in `port`
294            and `portName` fields.
295          returned: success
296          type: str
297    sslHealthCheck:
298      description:
299      - A nested object resource.
300      returned: success
301      type: complex
302      contains:
303        request:
304          description:
305          - The application data to send once the SSL connection has been established
306            (default value is empty). If both request and response are empty, the
307            connection establishment alone will indicate health. The request data
308            can only be ASCII.
309          returned: success
310          type: str
311        response:
312          description:
313          - The bytes to match against the beginning of the response data. If left
314            empty (the default value), any response will indicate health. The response
315            data can only be ASCII.
316          returned: success
317          type: str
318        port:
319          description:
320          - The TCP port number for the SSL health check request.
321          - The default value is 443.
322          returned: success
323          type: int
324        portName:
325          description:
326          - Port name as defined in InstanceGroup#NamedPort#name. If both port and
327            port_name are defined, port takes precedence.
328          returned: success
329          type: str
330        proxyHeader:
331          description:
332          - Specifies the type of proxy header to append before sending data to the
333            backend, either NONE or PROXY_V1. The default is NONE.
334          returned: success
335          type: str
336        portSpecification:
337          description:
338          - 'Specifies how port is selected for health checking, can be one of the
339            following values: * `USE_FIXED_PORT`: The port number in `port` is used
340            for health checking.'
341          - "* `USE_NAMED_PORT`: The `portName` is used for health checking."
342          - "* `USE_SERVING_PORT`: For NetworkEndpointGroup, the port specified for
343            each network endpoint is used for health checking. For other backends,
344            the port or named port specified in the Backend Service is used for health
345            checking."
346          - If not specified, SSL health check follows behavior specified in `port`
347            and `portName` fields.
348          returned: success
349          type: str
350'''
351
352################################################################################
353# Imports
354################################################################################
355from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
356import json
357
358################################################################################
359# Main
360################################################################################
361
362
363def main():
364    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str')))
365
366    if module._name == 'gcp_compute_health_check_facts':
367        module.deprecate("The 'gcp_compute_health_check_facts' module has been renamed to 'gcp_compute_health_check_info'", version='2.13')
368
369    if not module.params['scopes']:
370        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
371
372    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
373    module.exit_json(**return_value)
374
375
376def collection(module):
377    return "https://www.googleapis.com/compute/v1/projects/{project}/global/healthChecks".format(**module.params)
378
379
380def fetch_list(module, link, query):
381    auth = GcpSession(module, 'compute')
382    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
383
384
385def query_options(filters):
386    if not filters:
387        return ''
388
389    if len(filters) == 1:
390        return filters[0]
391    else:
392        queries = []
393        for f in filters:
394            # For multiple queries, all queries should have ()
395            if f[0] != '(' and f[-1] != ')':
396                queries.append("(%s)" % ''.join(f))
397            else:
398                queries.append(f)
399
400        return ' '.join(queries)
401
402
403def return_if_object(module, response):
404    # If not found, return nothing.
405    if response.status_code == 404:
406        return None
407
408    # If no content, return nothing.
409    if response.status_code == 204:
410        return None
411
412    try:
413        module.raise_for_status(response)
414        result = response.json()
415    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
416        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
417
418    if navigate_hash(result, ['error', 'errors']):
419        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
420
421    return result
422
423
424if __name__ == "__main__":
425    main()
426