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_url_map_info
33description:
34- Gather info for GCP UrlMap
35- This module was called C(gcp_compute_url_map_facts) before Ansible 2.9. The usage
36  has not changed.
37short_description: Gather info for GCP UrlMap
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 an URL map
56  gcp_compute_url_map_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    creationTimestamp:
71      description:
72      - Creation timestamp in RFC3339 text format.
73      returned: success
74      type: str
75    defaultService:
76      description:
77      - A reference to BackendService resource if none of the hostRules match.
78      returned: success
79      type: dict
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    hostRules:
87      description:
88      - The list of HostRules to use against the URL.
89      returned: success
90      type: complex
91      contains:
92        description:
93          description:
94          - An optional description of this HostRule. Provide this property when you
95            create the resource.
96          returned: success
97          type: str
98        hosts:
99          description:
100          - The list of host patterns to match. They must be valid hostnames, except
101            * will match any string of ([a-z0-9-.]*). In that case, * must be the
102            first character and must be followed in the pattern by either - or .
103          returned: success
104          type: list
105        pathMatcher:
106          description:
107          - The name of the PathMatcher to use to match the path portion of the URL
108            if the hostRule matches the URL's host portion.
109          returned: success
110          type: str
111    id:
112      description:
113      - The unique identifier for the resource.
114      returned: success
115      type: int
116    fingerprint:
117      description:
118      - Fingerprint of this resource. This field is used internally during updates
119        of this resource.
120      returned: success
121      type: str
122    name:
123      description:
124      - Name of the resource. Provided by the client when the resource is created.
125        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
126        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
127        which means the first character must be a lowercase letter, and all following
128        characters must be a dash, lowercase letter, or digit, except the last character,
129        which cannot be a dash.
130      returned: success
131      type: str
132    pathMatchers:
133      description:
134      - The list of named PathMatchers to use against the URL.
135      returned: success
136      type: complex
137      contains:
138        defaultService:
139          description:
140          - A reference to a BackendService resource. This will be used if none of
141            the pathRules defined by this PathMatcher is matched by the URL's path
142            portion.
143          returned: success
144          type: dict
145        description:
146          description:
147          - An optional description of this resource.
148          returned: success
149          type: str
150        name:
151          description:
152          - The name to which this PathMatcher is referred by the HostRule.
153          returned: success
154          type: str
155        pathRules:
156          description:
157          - The list of path rules.
158          returned: success
159          type: complex
160          contains:
161            paths:
162              description:
163              - 'The list of path patterns to match. Each must start with / and the
164                only place a * is allowed is at the end following a /. The string
165                fed to the path matcher does not include any text after the first
166                ? or #, and those chars are not allowed here.'
167              returned: success
168              type: list
169            service:
170              description:
171              - A reference to the BackendService resource if this rule is matched.
172              returned: success
173              type: dict
174    tests:
175      description:
176      - The list of expected URL mappings. Requests to update this UrlMap will succeed
177        only if all of the test cases pass.
178      returned: success
179      type: complex
180      contains:
181        description:
182          description:
183          - Description of this test case.
184          returned: success
185          type: str
186        host:
187          description:
188          - Host portion of the URL.
189          returned: success
190          type: str
191        path:
192          description:
193          - Path portion of the URL.
194          returned: success
195          type: str
196        service:
197          description:
198          - A reference to expected BackendService resource the given URL should be
199            mapped to.
200          returned: success
201          type: dict
202'''
203
204################################################################################
205# Imports
206################################################################################
207from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
208import json
209
210################################################################################
211# Main
212################################################################################
213
214
215def main():
216    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str')))
217
218    if module._name == 'gcp_compute_url_map_facts':
219        module.deprecate("The 'gcp_compute_url_map_facts' module has been renamed to 'gcp_compute_url_map_info'", version='2.13')
220
221    if not module.params['scopes']:
222        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
223
224    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
225    module.exit_json(**return_value)
226
227
228def collection(module):
229    return "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps".format(**module.params)
230
231
232def fetch_list(module, link, query):
233    auth = GcpSession(module, 'compute')
234    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
235
236
237def query_options(filters):
238    if not filters:
239        return ''
240
241    if len(filters) == 1:
242        return filters[0]
243    else:
244        queries = []
245        for f in filters:
246            # For multiple queries, all queries should have ()
247            if f[0] != '(' and f[-1] != ')':
248                queries.append("(%s)" % ''.join(f))
249            else:
250                queries.append(f)
251
252        return ' '.join(queries)
253
254
255def return_if_object(module, response):
256    # If not found, return nothing.
257    if response.status_code == 404:
258        return None
259
260    # If no content, return nothing.
261    if response.status_code == 204:
262        return None
263
264    try:
265        module.raise_for_status(response)
266        result = response.json()
267    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
268        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
269
270    if navigate_hash(result, ['error', 'errors']):
271        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
272
273    return result
274
275
276if __name__ == "__main__":
277    main()
278