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_region_disk_info
33description:
34- Gather info for GCP RegionDisk
35- This module was called C(gcp_compute_region_disk_facts) before Ansible 2.9. The
36  usage has not changed.
37short_description: Gather info for GCP RegionDisk
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    - A reference to the region where the disk resides.
54    required: true
55    type: str
56extends_documentation_fragment: gcp
57'''
58
59EXAMPLES = '''
60- name: get info on a region disk
61  gcp_compute_region_disk_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    labelFingerprint:
77      description:
78      - The fingerprint used for optimistic locking of this resource. Used internally
79        during updates.
80      returned: success
81      type: str
82    creationTimestamp:
83      description:
84      - Creation timestamp in RFC3339 text format.
85      returned: success
86      type: str
87    description:
88      description:
89      - An optional description of this resource. Provide this property when you create
90        the resource.
91      returned: success
92      type: str
93    id:
94      description:
95      - The unique identifier for the resource.
96      returned: success
97      type: int
98    lastAttachTimestamp:
99      description:
100      - Last attach timestamp in RFC3339 text format.
101      returned: success
102      type: str
103    lastDetachTimestamp:
104      description:
105      - Last detach timestamp in RFC3339 text format.
106      returned: success
107      type: str
108    labels:
109      description:
110      - Labels to apply to this disk. A list of key->value pairs.
111      returned: success
112      type: dict
113    licenses:
114      description:
115      - Any applicable publicly visible licenses.
116      returned: success
117      type: list
118    name:
119      description:
120      - Name of the resource. Provided by the client when the resource is created.
121        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
122        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
123        which means the first character must be a lowercase letter, and all following
124        characters must be a dash, lowercase letter, or digit, except the last character,
125        which cannot be a dash.
126      returned: success
127      type: str
128    sizeGb:
129      description:
130      - Size of the persistent disk, specified in GB. You can specify this field when
131        creating a persistent disk using the sourceImage or sourceSnapshot parameter,
132        or specify it alone to create an empty persistent disk.
133      - If you specify this field along with sourceImage or sourceSnapshot, the value
134        of sizeGb must not be less than the size of the sourceImage or the size of
135        the snapshot.
136      returned: success
137      type: int
138    users:
139      description:
140      - 'Links to the users of the disk (attached instances) in form: project/zones/zone/instances/instance
141        .'
142      returned: success
143      type: list
144    physicalBlockSizeBytes:
145      description:
146      - Physical block size of the persistent disk, in bytes. If not present in a
147        request, a default value is used. Currently supported sizes are 4096 and 16384,
148        other sizes may be added in the future.
149      - If an unsupported value is requested, the error message will list the supported
150        values for the caller's project.
151      returned: success
152      type: int
153    replicaZones:
154      description:
155      - URLs of the zones where the disk should be replicated to.
156      returned: success
157      type: list
158    type:
159      description:
160      - URL of the disk type resource describing which disk type to use to create
161        the disk. Provide this when creating the disk.
162      returned: success
163      type: str
164    region:
165      description:
166      - A reference to the region where the disk resides.
167      returned: success
168      type: str
169    diskEncryptionKey:
170      description:
171      - Encrypts the disk using a customer-supplied encryption key.
172      - After you encrypt a disk with a customer-supplied key, you must provide the
173        same key if you use the disk later (e.g. to create a disk snapshot or an image,
174        or to attach the disk to a virtual machine).
175      - Customer-supplied encryption keys do not protect access to metadata of the
176        disk.
177      - If you do not provide an encryption key when creating the disk, then the disk
178        will be encrypted using an automatically generated key and you do not need
179        to provide a key to use the disk later.
180      returned: success
181      type: complex
182      contains:
183        rawKey:
184          description:
185          - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648
186            base64 to either encrypt or decrypt this resource.
187          returned: success
188          type: str
189        sha256:
190          description:
191          - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption
192            key that protects this resource.
193          returned: success
194          type: str
195    sourceSnapshot:
196      description:
197      - The source snapshot used to create this disk. You can provide this as a partial
198        or full URL to the resource.
199      returned: success
200      type: dict
201    sourceSnapshotEncryptionKey:
202      description:
203      - The customer-supplied encryption key of the source snapshot. Required if the
204        source snapshot is protected by a customer-supplied encryption key.
205      returned: success
206      type: complex
207      contains:
208        rawKey:
209          description:
210          - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648
211            base64 to either encrypt or decrypt this resource.
212          returned: success
213          type: str
214        sha256:
215          description:
216          - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption
217            key that protects this resource.
218          returned: success
219          type: str
220    sourceSnapshotId:
221      description:
222      - The unique ID of the snapshot used to create this disk. This value identifies
223        the exact snapshot that was used to create this persistent disk. For example,
224        if you created the persistent disk from a snapshot that was later deleted
225        and recreated under the same name, the source snapshot ID would identify the
226        exact version of the snapshot that was used.
227      returned: success
228      type: str
229'''
230
231################################################################################
232# Imports
233################################################################################
234from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
235import json
236
237################################################################################
238# Main
239################################################################################
240
241
242def main():
243    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), region=dict(required=True, type='str')))
244
245    if module._name == 'gcp_compute_region_disk_facts':
246        module.deprecate("The 'gcp_compute_region_disk_facts' module has been renamed to 'gcp_compute_region_disk_info'", version='2.13')
247
248    if not module.params['scopes']:
249        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
250
251    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
252    module.exit_json(**return_value)
253
254
255def collection(module):
256    return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/disks".format(**module.params)
257
258
259def fetch_list(module, link, query):
260    auth = GcpSession(module, 'compute')
261    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
262
263
264def query_options(filters):
265    if not filters:
266        return ''
267
268    if len(filters) == 1:
269        return filters[0]
270    else:
271        queries = []
272        for f in filters:
273            # For multiple queries, all queries should have ()
274            if f[0] != '(' and f[-1] != ')':
275                queries.append("(%s)" % ''.join(f))
276            else:
277                queries.append(f)
278
279        return ' '.join(queries)
280
281
282def return_if_object(module, response):
283    # If not found, return nothing.
284    if response.status_code == 404:
285        return None
286
287    # If no content, return nothing.
288    if response.status_code == 204:
289        return None
290
291    try:
292        module.raise_for_status(response)
293        result = response.json()
294    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
295        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
296
297    if navigate_hash(result, ['error', 'errors']):
298        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
299
300    return result
301
302
303if __name__ == "__main__":
304    main()
305