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_instance_group_info
33description:
34- Gather info for GCP InstanceGroup
35- This module was called C(gcp_compute_instance_group_facts) before Ansible 2.9. The
36  usage has not changed.
37short_description: Gather info for GCP InstanceGroup
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  zone:
52    description:
53    - A reference to the zone where the instance group resides.
54    required: true
55    type: str
56extends_documentation_fragment: gcp
57'''
58
59EXAMPLES = '''
60- name: get info on an instance group
61  gcp_compute_instance_group_info:
62    zone: us-central1-a
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. Provide this property when you create
84        the resource.
85      returned: success
86      type: str
87    id:
88      description:
89      - A unique identifier for this instance group.
90      returned: success
91      type: int
92    name:
93      description:
94      - The name of the instance group.
95      - The name must be 1-63 characters long, and comply with RFC1035.
96      returned: success
97      type: str
98    namedPorts:
99      description:
100      - Assigns a name to a port number.
101      - 'For example: {name: "http", port: 80}.'
102      - This allows the system to reference ports by the assigned name instead of
103        a port number. Named ports can also contain multiple ports.
104      - 'For example: [{name: "http", port: 80},{name: "http", port: 8080}] Named
105        ports apply to all instances in this instance group.'
106      returned: success
107      type: complex
108      contains:
109        name:
110          description:
111          - The name for this named port.
112          - The name must be 1-63 characters long, and comply with RFC1035.
113          returned: success
114          type: str
115        port:
116          description:
117          - The port number, which can be a value between 1 and 65535.
118          returned: success
119          type: int
120    network:
121      description:
122      - The network to which all instances in the instance group belong.
123      returned: success
124      type: dict
125    region:
126      description:
127      - The region where the instance group is located (for regional resources).
128      returned: success
129      type: str
130    subnetwork:
131      description:
132      - The subnetwork to which all instances in the instance group belong.
133      returned: success
134      type: dict
135    zone:
136      description:
137      - A reference to the zone where the instance group resides.
138      returned: success
139      type: str
140    instances:
141      description:
142      - The list of instances associated with this InstanceGroup.
143      - All instances must be created before being added to an InstanceGroup.
144      - All instances not in this list will be removed from the InstanceGroup and
145        will not be deleted.
146      - Only the full identifier of the instance will be returned.
147      returned: success
148      type: list
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'), zone=dict(required=True, type='str')))
164
165    if module._name == 'gcp_compute_instance_group_facts':
166        module.deprecate("The 'gcp_compute_instance_group_facts' module has been renamed to 'gcp_compute_instance_group_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}/zones/{zone}/instanceGroups".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