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_router_info
33description:
34- Gather info for GCP Router
35- This module was called C(gcp_compute_router_facts) before Ansible 2.9. The usage
36  has not changed.
37short_description: Gather info for GCP Router
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
51  region:
52    description:
53    - Region where the router resides.
54    required: true
55    type: str
56extends_documentation_fragment: gcp
57'''
58
59EXAMPLES = '''
60- name: get info on a router
61  gcp_compute_router_info:
62    region: us-central1
63    filters:
64    - name = test_object
65    project: test_project
66    auth_kind: serviceaccount
67    service_account_file: "/tmp/auth.pem"
68'''
69
70RETURN = '''
71resources:
72  description: List of resources
73  returned: always
74  type: complex
75  contains:
76    id:
77      description:
78      - The unique identifier for the resource.
79      returned: success
80      type: int
81    creationTimestamp:
82      description:
83      - Creation timestamp in RFC3339 text format.
84      returned: success
85      type: str
86    name:
87      description:
88      - Name of the resource. The name must be 1-63 characters long, and comply with
89        RFC1035. Specifically, the name must be 1-63 characters long and match the
90        regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character
91        must be a lowercase letter, and all following characters must be a dash, lowercase
92        letter, or digit, except the last character, which cannot be a dash.
93      returned: success
94      type: str
95    description:
96      description:
97      - An optional description of this resource.
98      returned: success
99      type: str
100    network:
101      description:
102      - A reference to the network to which this router belongs.
103      returned: success
104      type: dict
105    bgp:
106      description:
107      - BGP information specific to this router.
108      returned: success
109      type: complex
110      contains:
111        asn:
112          description:
113          - Local BGP Autonomous System Number (ASN). Must be an RFC6996 private ASN,
114            either 16-bit or 32-bit. The value will be fixed for this router resource.
115            All VPN tunnels that link to this router will have the same local ASN.
116          returned: success
117          type: int
118        advertiseMode:
119          description:
120          - User-specified flag to indicate which mode to use for advertisement.
121          - 'Valid values of this enum field are: DEFAULT, CUSTOM .'
122          returned: success
123          type: str
124        advertisedGroups:
125          description:
126          - User-specified list of prefix groups to advertise in custom mode.
127          - This field can only be populated if advertiseMode is CUSTOM and is advertised
128            to all peers of the router. These groups will be advertised in addition
129            to any specified prefixes. Leave this field blank to advertise no custom
130            groups.
131          - 'This enum field has the one valid value: ALL_SUBNETS .'
132          returned: success
133          type: list
134        advertisedIpRanges:
135          description:
136          - User-specified list of individual IP ranges to advertise in custom mode.
137            This field can only be populated if advertiseMode is CUSTOM and is advertised
138            to all peers of the router. These IP ranges will be advertised in addition
139            to any specified groups.
140          - Leave this field blank to advertise no custom IP ranges.
141          returned: success
142          type: complex
143          contains:
144            range:
145              description:
146              - The IP range to advertise. The value must be a CIDR-formatted string.
147              returned: success
148              type: str
149            description:
150              description:
151              - User-specified description for the IP range.
152              returned: success
153              type: str
154    region:
155      description:
156      - Region where the router resides.
157      returned: success
158      type: str
159'''
160
161################################################################################
162# Imports
163################################################################################
164from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
165import json
166
167################################################################################
168# Main
169################################################################################
170
171
172def main():
173    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), region=dict(required=True, type='str')))
174
175    if module._name == 'gcp_compute_router_facts':
176        module.deprecate("The 'gcp_compute_router_facts' module has been renamed to 'gcp_compute_router_info'", version='2.13')
177
178    if not module.params['scopes']:
179        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
180
181    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
182    module.exit_json(**return_value)
183
184
185def collection(module):
186    return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/routers".format(**module.params)
187
188
189def fetch_list(module, link, query):
190    auth = GcpSession(module, 'compute')
191    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
192
193
194def query_options(filters):
195    if not filters:
196        return ''
197
198    if len(filters) == 1:
199        return filters[0]
200    else:
201        queries = []
202        for f in filters:
203            # For multiple queries, all queries should have ()
204            if f[0] != '(' and f[-1] != ')':
205                queries.append("(%s)" % ''.join(f))
206            else:
207                queries.append(f)
208
209        return ' '.join(queries)
210
211
212def return_if_object(module, response):
213    # If not found, return nothing.
214    if response.status_code == 404:
215        return None
216
217    # If no content, return nothing.
218    if response.status_code == 204:
219        return None
220
221    try:
222        module.raise_for_status(response)
223        result = response.json()
224    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
225        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
226
227    if navigate_hash(result, ['error', 'errors']):
228        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
229
230    return result
231
232
233if __name__ == "__main__":
234    main()
235