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_global_forwarding_rule_info
33description:
34- Gather info for GCP GlobalForwardingRule
35- This module was called C(gcp_compute_global_forwarding_rule_facts) before Ansible
36  2.9. The usage has not changed.
37short_description: Gather info for GCP GlobalForwardingRule
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 a global forwarding rule
56  gcp_compute_global_forwarding_rule_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    description:
76      description:
77      - An optional description of this resource. Provide this property when you create
78        the resource.
79      returned: success
80      type: str
81    id:
82      description:
83      - The unique identifier for the resource.
84      returned: success
85      type: int
86    IPAddress:
87      description:
88      - The IP address that this forwarding rule is serving on behalf of.
89      - Addresses are restricted based on the forwarding rule's load balancing scheme
90        (EXTERNAL or INTERNAL) and scope (global or regional).
91      - When the load balancing scheme is EXTERNAL, for global forwarding rules, the
92        address must be a global IP, and for regional forwarding rules, the address
93        must live in the same region as the forwarding rule. If this field is empty,
94        an ephemeral IPv4 address from the same scope (global or regional) will be
95        assigned. A regional forwarding rule supports IPv4 only. A global forwarding
96        rule supports either IPv4 or IPv6.
97      - When the load balancing scheme is INTERNAL, this can only be an RFC 1918 IP
98        address belonging to the network/subnet configured for the forwarding rule.
99        By default, if this field is empty, an ephemeral internal IP address will
100        be automatically allocated from the IP range of the subnet or network configured
101        for this forwarding rule.
102      - 'An address can be specified either by a literal IP address or a URL reference
103        to an existing Address resource. The following examples are all valid: * 100.1.2.3
104        * U(https://www.googleapis.com/compute/v1/projects/project/regions/region/addresses/address)
105        * projects/project/regions/region/addresses/address * regions/region/addresses/address
106        * global/addresses/address * address .'
107      returned: success
108      type: str
109    IPProtocol:
110      description:
111      - The IP protocol to which this rule applies. Valid options are TCP, UDP, ESP,
112        AH, SCTP or ICMP. When the load balancing scheme is INTERNAL_SELF_MANAGED,
113        only TCP is valid.
114      returned: success
115      type: str
116    ipVersion:
117      description:
118      - The IP Version that will be used by this global forwarding rule.
119      - Valid options are IPV4 or IPV6.
120      returned: success
121      type: str
122    loadBalancingScheme:
123      description:
124      - This signifies what the GlobalForwardingRule will be used for.
125      - 'The value of INTERNAL_SELF_MANAGED means that this will be used for Internal
126        Global HTTP(S) LB. The value of EXTERNAL means that this will be used for
127        External Global Load Balancing (HTTP(S) LB, External TCP/UDP LB, SSL Proxy)
128        NOTE: Currently global forwarding rules cannot be used for INTERNAL load balancing.'
129      returned: success
130      type: str
131    name:
132      description:
133      - Name of the resource; provided by the client when the resource is created.
134        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
135        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
136        which means the first character must be a lowercase letter, and all following
137        characters must be a dash, lowercase letter, or digit, except the last character,
138        which cannot be a dash.
139      returned: success
140      type: str
141    network:
142      description:
143      - This field is not used for external load balancing.
144      - For INTERNAL_SELF_MANAGED load balancing, this field identifies the network
145        that the load balanced IP should belong to for this global forwarding rule.
146        If this field is not specified, the default network will be used.
147      returned: success
148      type: dict
149    portRange:
150      description:
151      - This field is used along with the target field for TargetHttpProxy, TargetHttpsProxy,
152        TargetSslProxy, TargetTcpProxy, TargetVpnGateway, TargetPool, TargetInstance.
153      - Applicable only when IPProtocol is TCP, UDP, or SCTP, only packets addressed
154        to ports in the specified range will be forwarded to target.
155      - Forwarding rules with the same [IPAddress, IPProtocol] pair must have disjoint
156        port ranges.
157      - 'Some types of forwarding target have constraints on the acceptable ports:
158        * TargetHttpProxy: 80, 8080 * TargetHttpsProxy: 443 * TargetTcpProxy: 25,
159        43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 5222 * TargetSslProxy:
160        25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 5222 * TargetVpnGateway:
161        500, 4500 .'
162      returned: success
163      type: str
164    target:
165      description:
166      - The URL of the target resource to receive the matched traffic.
167      - The forwarded traffic must be of a type appropriate to the target object.
168      returned: success
169      type: str
170'''
171
172################################################################################
173# Imports
174################################################################################
175from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
176import json
177
178################################################################################
179# Main
180################################################################################
181
182
183def main():
184    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str')))
185
186    if module._name == 'gcp_compute_global_forwarding_rule_facts':
187        module.deprecate("The 'gcp_compute_global_forwarding_rule_facts' module has been renamed to 'gcp_compute_global_forwarding_rule_info'", version='2.13')
188
189    if not module.params['scopes']:
190        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
191
192    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
193    module.exit_json(**return_value)
194
195
196def collection(module):
197    return "https://www.googleapis.com/compute/v1/projects/{project}/global/forwardingRules".format(**module.params)
198
199
200def fetch_list(module, link, query):
201    auth = GcpSession(module, 'compute')
202    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
203
204
205def query_options(filters):
206    if not filters:
207        return ''
208
209    if len(filters) == 1:
210        return filters[0]
211    else:
212        queries = []
213        for f in filters:
214            # For multiple queries, all queries should have ()
215            if f[0] != '(' and f[-1] != ')':
216                queries.append("(%s)" % ''.join(f))
217            else:
218                queries.append(f)
219
220        return ' '.join(queries)
221
222
223def return_if_object(module, response):
224    # If not found, return nothing.
225    if response.status_code == 404:
226        return None
227
228    # If no content, return nothing.
229    if response.status_code == 204:
230        return None
231
232    try:
233        module.raise_for_status(response)
234        result = response.json()
235    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
236        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
237
238    if navigate_hash(result, ['error', 'errors']):
239        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
240
241    return result
242
243
244if __name__ == "__main__":
245    main()
246