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_vpn_tunnel_info
33description:
34- Gather info for GCP VpnTunnel
35- This module was called C(gcp_compute_vpn_tunnel_facts) before Ansible 2.9. The usage
36  has not changed.
37short_description: Gather info for GCP VpnTunnel
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 where the tunnel is located.
54    required: true
55    type: str
56extends_documentation_fragment: gcp
57'''
58
59EXAMPLES = '''
60- name: get info on a vpn tunnel
61  gcp_compute_vpn_tunnel_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    name:
82      description:
83      - Name of the resource. The name must be 1-63 characters long, and comply with
84        RFC1035. Specifically, the name must be 1-63 characters long and match the
85        regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character
86        must be a lowercase letter, and all following characters must be a dash, lowercase
87        letter, or digit, except the last character, which cannot be a dash.
88      returned: success
89      type: str
90    description:
91      description:
92      - An optional description of this resource.
93      returned: success
94      type: str
95    targetVpnGateway:
96      description:
97      - URL of the Target VPN gateway with which this VPN tunnel is associated.
98      returned: success
99      type: dict
100    router:
101      description:
102      - URL of router resource to be used for dynamic routing.
103      returned: success
104      type: dict
105    peerIp:
106      description:
107      - IP address of the peer VPN gateway. Only IPv4 is supported.
108      returned: success
109      type: str
110    sharedSecret:
111      description:
112      - Shared secret used to set the secure session between the Cloud VPN gateway
113        and the peer VPN gateway.
114      returned: success
115      type: str
116    sharedSecretHash:
117      description:
118      - Hash of the shared secret.
119      returned: success
120      type: str
121    ikeVersion:
122      description:
123      - IKE protocol version to use when establishing the VPN tunnel with peer VPN
124        gateway.
125      - Acceptable IKE versions are 1 or 2. Default version is 2.
126      returned: success
127      type: int
128    localTrafficSelector:
129      description:
130      - Local traffic selector to use when establishing the VPN tunnel with peer VPN
131        gateway. The value should be a CIDR formatted string, for example `192.168.0.0/16`.
132        The ranges should be disjoint.
133      - Only IPv4 is supported.
134      returned: success
135      type: list
136    remoteTrafficSelector:
137      description:
138      - Remote traffic selector to use when establishing the VPN tunnel with peer
139        VPN gateway. The value should be a CIDR formatted string, for example `192.168.0.0/16`.
140        The ranges should be disjoint.
141      - Only IPv4 is supported.
142      returned: success
143      type: list
144    region:
145      description:
146      - The region where the tunnel is located.
147      returned: success
148      type: str
149'''
150
151################################################################################
152# Imports
153################################################################################
154from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
155import json
156
157################################################################################
158# Main
159################################################################################
160
161
162def main():
163    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), region=dict(required=True, type='str')))
164
165    if module._name == 'gcp_compute_vpn_tunnel_facts':
166        module.deprecate("The 'gcp_compute_vpn_tunnel_facts' module has been renamed to 'gcp_compute_vpn_tunnel_info'", version='2.13')
167
168    if not module.params['scopes']:
169        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
170
171    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
172    module.exit_json(**return_value)
173
174
175def collection(module):
176    return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/vpnTunnels".format(**module.params)
177
178
179def fetch_list(module, link, query):
180    auth = GcpSession(module, 'compute')
181    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
182
183
184def query_options(filters):
185    if not filters:
186        return ''
187
188    if len(filters) == 1:
189        return filters[0]
190    else:
191        queries = []
192        for f in filters:
193            # For multiple queries, all queries should have ()
194            if f[0] != '(' and f[-1] != ')':
195                queries.append("(%s)" % ''.join(f))
196            else:
197                queries.append(f)
198
199        return ' '.join(queries)
200
201
202def return_if_object(module, response):
203    # If not found, return nothing.
204    if response.status_code == 404:
205        return None
206
207    # If no content, return nothing.
208    if response.status_code == 204:
209        return None
210
211    try:
212        module.raise_for_status(response)
213        result = response.json()
214    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
215        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
216
217    if navigate_hash(result, ['error', 'errors']):
218        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
219
220    return result
221
222
223if __name__ == "__main__":
224    main()
225