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_interconnect_attachment_info
33description:
34- Gather info for GCP InterconnectAttachment
35- This module was called C(gcp_compute_interconnect_attachment_facts) before Ansible
36  2.9. The usage has not changed.
37short_description: Gather info for GCP InterconnectAttachment
38version_added: 2.8
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 regional interconnect attachment resides.
54    required: true
55    type: str
56extends_documentation_fragment: gcp
57'''
58
59EXAMPLES = '''
60- name: get info on an interconnect attachment
61  gcp_compute_interconnect_attachment_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    adminEnabled:
77      description:
78      - Whether the VLAN attachment is enabled or disabled. When using PARTNER type
79        this will Pre-Activate the interconnect attachment .
80      returned: success
81      type: bool
82    cloudRouterIpAddress:
83      description:
84      - IPv4 address + prefix length to be configured on Cloud Router Interface for
85        this interconnect attachment.
86      returned: success
87      type: str
88    customerRouterIpAddress:
89      description:
90      - IPv4 address + prefix length to be configured on the customer router subinterface
91        for this interconnect attachment.
92      returned: success
93      type: str
94    interconnect:
95      description:
96      - URL of the underlying Interconnect object that this attachment's traffic will
97        traverse through. Required if type is DEDICATED, must not be set if type is
98        PARTNER.
99      returned: success
100      type: str
101    description:
102      description:
103      - An optional description of this resource.
104      returned: success
105      type: str
106    bandwidth:
107      description:
108      - Provisioned bandwidth capacity for the interconnect attachment.
109      - For attachments of type DEDICATED, the user can set the bandwidth.
110      - For attachments of type PARTNER, the Google Partner that is operating the
111        interconnect must set the bandwidth.
112      - Output only for PARTNER type, mutable for PARTNER_PROVIDER and DEDICATED,
113        Defaults to BPS_10G .
114      returned: success
115      type: str
116    edgeAvailabilityDomain:
117      description:
118      - Desired availability domain for the attachment. Only available for type PARTNER,
119        at creation time. For improved reliability, customers should configure a pair
120        of attachments with one per availability domain. The selected availability
121        domain will be provided to the Partner via the pairing key so that the provisioned
122        circuit will lie in the specified domain. If not specified, the value will
123        default to AVAILABILITY_DOMAIN_ANY.
124      returned: success
125      type: str
126    pairingKey:
127      description:
128      - '[Output only for type PARTNER. Not present for DEDICATED]. The opaque identifier
129        of an PARTNER attachment used to initiate provisioning with a selected partner.
130        Of the form "XXXXX/region/domain" .'
131      returned: success
132      type: str
133    partnerAsn:
134      description:
135      - "[Output only for type PARTNER. Not present for DEDICATED]. Optional BGP ASN
136        for the router that should be supplied by a layer 3 Partner if they configured
137        BGP on behalf of the customer."
138      returned: success
139      type: str
140    privateInterconnectInfo:
141      description:
142      - Information specific to an InterconnectAttachment. This property is populated
143        if the interconnect that this is attached to is of type DEDICATED.
144      returned: success
145      type: complex
146      contains:
147        tag8021q:
148          description:
149          - 802.1q encapsulation tag to be used for traffic between Google and the
150            customer, going to and from this network and region.
151          returned: success
152          type: int
153    type:
154      description:
155      - The type of InterconnectAttachment you wish to create. Defaults to DEDICATED.
156      returned: success
157      type: str
158    state:
159      description:
160      - "[Output Only] The current state of this attachment's functionality."
161      returned: success
162      type: str
163    googleReferenceId:
164      description:
165      - Google reference ID, to be used when raising support tickets with Google or
166        otherwise to debug backend connectivity issues.
167      returned: success
168      type: str
169    router:
170      description:
171      - URL of the cloud router to be used for dynamic routing. This router must be
172        in the same region as this InterconnectAttachment. The InterconnectAttachment
173        will automatically connect the Interconnect to the network & region within
174        which the Cloud Router is configured.
175      returned: success
176      type: dict
177    creationTimestamp:
178      description:
179      - Creation timestamp in RFC3339 text format.
180      returned: success
181      type: str
182    id:
183      description:
184      - The unique identifier for the resource. This identifier is defined by the
185        server.
186      returned: success
187      type: str
188    name:
189      description:
190      - Name of the resource. Provided by the client when the resource is created.
191        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
192        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
193        which means the first character must be a lowercase letter, and all following
194        characters must be a dash, lowercase letter, or digit, except the last character,
195        which cannot be a dash.
196      returned: success
197      type: str
198    candidateSubnets:
199      description:
200      - Up to 16 candidate prefixes that can be used to restrict the allocation of
201        cloudRouterIpAddress and customerRouterIpAddress for this attachment.
202      - All prefixes must be within link-local address space (169.254.0.0/16) and
203        must be /29 or shorter (/28, /27, etc). Google will attempt to select an unused
204        /29 from the supplied candidate prefix(es). The request will fail if all possible
205        /29s are in use on Google's edge. If not supplied, Google will randomly select
206        an unused /29 from all of link-local space.
207      returned: success
208      type: list
209    vlanTag8021q:
210      description:
211      - The IEEE 802.1Q VLAN tag for this attachment, in the range 2-4094. When using
212        PARTNER type this will be managed upstream.
213      returned: success
214      type: int
215    region:
216      description:
217      - Region where the regional interconnect attachment resides.
218      returned: success
219      type: str
220'''
221
222################################################################################
223# Imports
224################################################################################
225from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
226import json
227
228################################################################################
229# Main
230################################################################################
231
232
233def main():
234    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), region=dict(required=True, type='str')))
235
236    if module._name == 'gcp_compute_interconnect_attachment_facts':
237        module.deprecate(
238            "The 'gcp_compute_interconnect_attachment_facts' module has been renamed to 'gcp_compute_interconnect_attachment_info'", version='2.13'
239        )
240
241    if not module.params['scopes']:
242        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
243
244    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
245    module.exit_json(**return_value)
246
247
248def collection(module):
249    return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/interconnectAttachments".format(**module.params)
250
251
252def fetch_list(module, link, query):
253    auth = GcpSession(module, 'compute')
254    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
255
256
257def query_options(filters):
258    if not filters:
259        return ''
260
261    if len(filters) == 1:
262        return filters[0]
263    else:
264        queries = []
265        for f in filters:
266            # For multiple queries, all queries should have ()
267            if f[0] != '(' and f[-1] != ')':
268                queries.append("(%s)" % ''.join(f))
269            else:
270                queries.append(f)
271
272        return ' '.join(queries)
273
274
275def return_if_object(module, response):
276    # If not found, return nothing.
277    if response.status_code == 404:
278        return None
279
280    # If no content, return nothing.
281    if response.status_code == 204:
282        return None
283
284    try:
285        module.raise_for_status(response)
286        result = response.json()
287    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
288        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
289
290    if navigate_hash(result, ['error', 'errors']):
291        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
292
293    return result
294
295
296if __name__ == "__main__":
297    main()
298