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_ssl_certificate_info
33description:
34- Gather info for GCP SslCertificate
35- This module was called C(gcp_compute_ssl_certificate_facts) before Ansible 2.9.
36  The usage has not changed.
37short_description: Gather info for GCP SslCertificate
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 SSL certificate
56  gcp_compute_ssl_certificate_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    certificate:
71      description:
72      - The certificate in PEM format.
73      - The certificate chain must be no greater than 5 certs long.
74      - The chain must include at least one intermediate cert.
75      returned: success
76      type: str
77    creationTimestamp:
78      description:
79      - Creation timestamp in RFC3339 text format.
80      returned: success
81      type: str
82    description:
83      description:
84      - An optional description of this resource.
85      returned: success
86      type: str
87    id:
88      description:
89      - The unique identifier for the resource.
90      returned: success
91      type: int
92    name:
93      description:
94      - Name of the resource. Provided by the client when the resource is created.
95        The name must be 1-63 characters long, and comply with RFC1035. Specifically,
96        the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`
97        which means the first character must be a lowercase letter, and all following
98        characters must be a dash, lowercase letter, or digit, except the last character,
99        which cannot be a dash.
100      returned: success
101      type: str
102    privateKey:
103      description:
104      - The write-only private key in PEM format.
105      returned: success
106      type: str
107'''
108
109################################################################################
110# Imports
111################################################################################
112from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
113import json
114
115################################################################################
116# Main
117################################################################################
118
119
120def main():
121    module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str')))
122
123    if module._name == 'gcp_compute_ssl_certificate_facts':
124        module.deprecate("The 'gcp_compute_ssl_certificate_facts' module has been renamed to 'gcp_compute_ssl_certificate_info'", version='2.13')
125
126    if not module.params['scopes']:
127        module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
128
129    return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))}
130    module.exit_json(**return_value)
131
132
133def collection(module):
134    return "https://www.googleapis.com/compute/v1/projects/{project}/global/sslCertificates".format(**module.params)
135
136
137def fetch_list(module, link, query):
138    auth = GcpSession(module, 'compute')
139    return auth.list(link, return_if_object, array_name='items', params={'filter': query})
140
141
142def query_options(filters):
143    if not filters:
144        return ''
145
146    if len(filters) == 1:
147        return filters[0]
148    else:
149        queries = []
150        for f in filters:
151            # For multiple queries, all queries should have ()
152            if f[0] != '(' and f[-1] != ')':
153                queries.append("(%s)" % ''.join(f))
154            else:
155                queries.append(f)
156
157        return ' '.join(queries)
158
159
160def return_if_object(module, response):
161    # If not found, return nothing.
162    if response.status_code == 404:
163        return None
164
165    # If no content, return nothing.
166    if response.status_code == 204:
167        return None
168
169    try:
170        module.raise_for_status(response)
171        result = response.json()
172    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
173        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
174
175    if navigate_hash(result, ['error', 'errors']):
176        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
177
178    return result
179
180
181if __name__ == "__main__":
182    main()
183