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_snapshot_info
33description:
34- Gather info for GCP Snapshot
35short_description: Gather info for GCP Snapshot
36version_added: 2.9
37author: Google Inc. (@googlecloudplatform)
38requirements:
39- python >= 2.6
40- requests >= 2.18.4
41- google-auth >= 1.3.0
42options:
43  filters:
44    description:
45    - A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters).
46    - Each additional filter in the list will act be added as an AND condition (filter1
47      and filter2) .
48    type: list
49extends_documentation_fragment: gcp
50'''
51
52EXAMPLES = '''
53- name: get info on a snapshot
54  gcp_compute_snapshot_info:
55    filters:
56    - name = test_object
57    project: test_project
58    auth_kind: serviceaccount
59    service_account_file: "/tmp/auth.pem"
60'''
61
62RETURN = '''
63resources:
64  description: List of resources
65  returned: always
66  type: complex
67  contains:
68    creationTimestamp:
69      description:
70      - Creation timestamp in RFC3339 text format.
71      returned: success
72      type: str
73    id:
74      description:
75      - The unique identifier for the resource.
76      returned: success
77      type: int
78    diskSizeGb:
79      description:
80      - Size of the snapshot, specified in GB.
81      returned: success
82      type: int
83    name:
84      description:
85      - Name of the resource; provided by the client when the resource is created.
86        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
87        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
88        which means the first character must be a lowercase letter, and all following
89        characters must be a dash, lowercase letter, or digit, except the last character,
90        which cannot be a dash.
91      returned: success
92      type: str
93    description:
94      description:
95      - An optional description of this resource.
96      returned: success
97      type: str
98    storageBytes:
99      description:
100      - A size of the the storage used by the snapshot. As snapshots share storage,
101        this number is expected to change with snapshot creation/deletion.
102      returned: success
103      type: int
104    licenses:
105      description:
106      - A list of public visible licenses that apply to this snapshot. This can be
107        because the original image had licenses attached (such as a Windows image).
108        snapshotEncryptionKey nested object Encrypts the snapshot using a customer-supplied
109        encryption key.
110      returned: success
111      type: list
112    labels:
113      description:
114      - Labels to apply to this Snapshot.
115      returned: success
116      type: dict
117    labelFingerprint:
118      description:
119      - The fingerprint used for optimistic locking of this resource. Used internally
120        during updates.
121      returned: success
122      type: str
123    sourceDisk:
124      description:
125      - A reference to the disk used to create this snapshot.
126      returned: success
127      type: dict
128    zone:
129      description:
130      - A reference to the zone where the disk is hosted.
131      returned: success
132      type: str
133    snapshotEncryptionKey:
134      description:
135      - The customer-supplied encryption key of the snapshot. Required if the source
136        snapshot is protected by a customer-supplied encryption key.
137      returned: success
138      type: complex
139      contains:
140        rawKey:
141          description:
142          - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648
143            base64 to either encrypt or decrypt this resource.
144          returned: success
145          type: str
146        sha256:
147          description:
148          - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption
149            key that protects this resource.
150          returned: success
151          type: str
152        kmsKeyName:
153          description:
154          - The name of the encryption key that is stored in Google Cloud KMS.
155          returned: success
156          type: str
157    sourceDiskEncryptionKey:
158      description:
159      - The customer-supplied encryption key of the source snapshot. Required if the
160        source snapshot is protected by a customer-supplied encryption key.
161      returned: success
162      type: complex
163      contains:
164        rawKey:
165          description:
166          - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648
167            base64 to either encrypt or decrypt this resource.
168          returned: success
169          type: str
170        kmsKeyName:
171          description:
172          - The name of the encryption key that is stored in Google Cloud KMS.
173          returned: success
174          type: str
175'''
176
177################################################################################
178# Imports
179################################################################################
180from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
181import json
182
183################################################################################
184# Main
185################################################################################
186
187
188def main():
189    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str')))
190
191    if not module.params['scopes']:
192        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
193
194    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
195    module.exit_json(**return_value)
196
197
198def collection(module):
199    return "https://www.googleapis.com/compute/v1/projects/{project}/global/snapshots".format(**module.params)
200
201
202def fetch_list(module, link, query):
203    auth = GcpSession(module, 'compute')
204    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
205
206
207def query_options(filters):
208    if not filters:
209        return ''
210
211    if len(filters) == 1:
212        return filters[0]
213    else:
214        queries = []
215        for f in filters:
216            # For multiple queries, all queries should have ()
217            if f[0] != '(' and f[-1] != ')':
218                queries.append("(%s)" % ''.join(f))
219            else:
220                queries.append(f)
221
222        return ' '.join(queries)
223
224
225def return_if_object(module, response):
226    # If not found, return nothing.
227    if response.status_code == 404:
228        return None
229
230    # If no content, return nothing.
231    if response.status_code == 204:
232        return None
233
234    try:
235        module.raise_for_status(response)
236        result = response.json()
237    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
238        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
239
240    if navigate_hash(result, ['error', 'errors']):
241        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
242
243    return result
244
245
246if __name__ == "__main__":
247    main()
248