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_target_vpn_gateway_info
33description:
34- Gather info for GCP TargetVpnGateway
35- This module was called C(gcp_compute_target_vpn_gateway_facts) before Ansible 2.9.
36  The usage has not changed.
37short_description: Gather info for GCP TargetVpnGateway
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    - The region this gateway should sit in.
54    required: true
55    type: str
56extends_documentation_fragment: gcp
57'''
58
59EXAMPLES = '''
60- name: get info on a target vpn gateway
61  gcp_compute_target_vpn_gateway_info:
62    region: us-west1
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    creationTimestamp:
77      description:
78      - Creation timestamp in RFC3339 text format.
79      returned: success
80      type: str
81    description:
82      description:
83      - An optional description of this resource.
84      returned: success
85      type: str
86    name:
87      description:
88      - Name of the resource. Provided by the client when the resource is created.
89        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
90        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
91        which means the first character must be a lowercase letter, and all following
92        characters must be a dash, lowercase letter, or digit, except the last character,
93        which cannot be a dash.
94      returned: success
95      type: str
96    id:
97      description:
98      - The unique identifier for the resource.
99      returned: success
100      type: int
101    network:
102      description:
103      - The network this VPN gateway is accepting traffic for.
104      returned: success
105      type: dict
106    tunnels:
107      description:
108      - A list of references to VpnTunnel resources associated with this VPN gateway.
109      returned: success
110      type: list
111    forwardingRules:
112      description:
113      - A list of references to the ForwardingRule resources associated with this
114        VPN gateway.
115      returned: success
116      type: list
117    region:
118      description:
119      - The region this gateway should sit in.
120      returned: success
121      type: str
122'''
123
124################################################################################
125# Imports
126################################################################################
127from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
128import json
129
130################################################################################
131# Main
132################################################################################
133
134
135def main():
136    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), region=dict(required=True, type='str')))
137
138    if module._name == 'gcp_compute_target_vpn_gateway_facts':
139        module.deprecate("The 'gcp_compute_target_vpn_gateway_facts' module has been renamed to 'gcp_compute_target_vpn_gateway_info'", version='2.13')
140
141    if not module.params['scopes']:
142        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
143
144    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
145    module.exit_json(**return_value)
146
147
148def collection(module):
149    return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetVpnGateways".format(**module.params)
150
151
152def fetch_list(module, link, query):
153    auth = GcpSession(module, 'compute')
154    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
155
156
157def query_options(filters):
158    if not filters:
159        return ''
160
161    if len(filters) == 1:
162        return filters[0]
163    else:
164        queries = []
165        for f in filters:
166            # For multiple queries, all queries should have ()
167            if f[0] != '(' and f[-1] != ')':
168                queries.append("(%s)" % ''.join(f))
169            else:
170                queries.append(f)
171
172        return ' '.join(queries)
173
174
175def return_if_object(module, response):
176    # If not found, return nothing.
177    if response.status_code == 404:
178        return None
179
180    # If no content, return nothing.
181    if response.status_code == 204:
182        return None
183
184    try:
185        module.raise_for_status(response)
186        result = response.json()
187    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
188        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
189
190    if navigate_hash(result, ['error', 'errors']):
191        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
192
193    return result
194
195
196if __name__ == "__main__":
197    main()
198