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_sql_instance_info
33description:
34- Gather info for GCP Instance
35- This module was called C(gcp_sql_instance_facts) before Ansible 2.9. The usage has
36  not changed.
37short_description: Gather info for GCP Instance
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: {}
45extends_documentation_fragment: gcp
46'''
47
48EXAMPLES = '''
49- name: get info on an instance
50  gcp_sql_instance_info:
51    project: test_project
52    auth_kind: serviceaccount
53    service_account_file: "/tmp/auth.pem"
54'''
55
56RETURN = '''
57resources:
58  description: List of resources
59  returned: always
60  type: complex
61  contains:
62    backendType:
63      description:
64      - "* FIRST_GEN: First Generation instance. MySQL only."
65      - "* SECOND_GEN: Second Generation instance or PostgreSQL instance."
66      - "* EXTERNAL: A database server that is not managed by Google."
67      returned: success
68      type: str
69    connectionName:
70      description:
71      - Connection name of the Cloud SQL instance used in connection strings.
72      returned: success
73      type: str
74    databaseVersion:
75      description:
76      - The database engine type and version. For First Generation instances, can
77        be MYSQL_5_5, or MYSQL_5_6. For Second Generation instances, can be MYSQL_5_6
78        or MYSQL_5_7. Defaults to MYSQL_5_6.
79      - 'PostgreSQL instances: POSTGRES_9_6 The databaseVersion property can not be
80        changed after instance creation.'
81      returned: success
82      type: str
83    failoverReplica:
84      description:
85      - The name and status of the failover replica. This property is applicable only
86        to Second Generation instances.
87      returned: success
88      type: complex
89      contains:
90        available:
91          description:
92          - The availability status of the failover replica. A false status indicates
93            that the failover replica is out of sync. The master can only failover
94            to the failover replica when the status is true.
95          returned: success
96          type: bool
97        name:
98          description:
99          - The name of the failover replica. If specified at instance creation, a
100            failover replica is created for the instance. The name doesn't include
101            the project ID. This property is applicable only to Second Generation
102            instances.
103          returned: success
104          type: str
105    instanceType:
106      description:
107      - The instance type. This can be one of the following.
108      - "* CLOUD_SQL_INSTANCE: A Cloud SQL instance that is not replicating from a
109        master."
110      - "* ON_PREMISES_INSTANCE: An instance running on the customer's premises."
111      - "* READ_REPLICA_INSTANCE: A Cloud SQL instance configured as a read-replica."
112      returned: success
113      type: str
114    ipAddresses:
115      description:
116      - The assigned IP addresses for the instance.
117      returned: success
118      type: complex
119      contains:
120        ipAddress:
121          description:
122          - The IP address assigned.
123          returned: success
124          type: str
125        timeToRetire:
126          description:
127          - The due time for this IP to be retired in RFC 3339 format, for example
128            2012-11-15T16:19:00.094Z. This field is only available when the IP is
129            scheduled to be retired.
130          returned: success
131          type: str
132        type:
133          description:
134          - The type of this IP address. A PRIMARY address is an address that can
135            accept incoming connections. An OUTGOING address is the source address
136            of connections originating from the instance, if supported.
137          returned: success
138          type: str
139    ipv6Address:
140      description:
141      - The IPv6 address assigned to the instance. This property is applicable only
142        to First Generation instances.
143      returned: success
144      type: str
145    masterInstanceName:
146      description:
147      - The name of the instance which will act as master in the replication setup.
148      returned: success
149      type: str
150    maxDiskSize:
151      description:
152      - The maximum disk size of the instance in bytes.
153      returned: success
154      type: int
155    name:
156      description:
157      - Name of the Cloud SQL instance. This does not include the project ID.
158      returned: success
159      type: str
160    region:
161      description:
162      - The geographical region. Defaults to us-central or us-central1 depending on
163        the instance type (First Generation or Second Generation/PostgreSQL).
164      returned: success
165      type: str
166    replicaConfiguration:
167      description:
168      - Configuration specific to failover replicas and read replicas.
169      returned: success
170      type: complex
171      contains:
172        failoverTarget:
173          description:
174          - Specifies if the replica is the failover target. If the field is set to
175            true the replica will be designated as a failover replica.
176          - In case the master instance fails, the replica instance will be promoted
177            as the new master instance.
178          - Only one replica can be specified as failover target, and the replica
179            has to be in different zone with the master instance.
180          returned: success
181          type: bool
182        mysqlReplicaConfiguration:
183          description:
184          - MySQL specific configuration when replicating from a MySQL on-premises
185            master. Replication configuration information such as the username, password,
186            certificates, and keys are not stored in the instance metadata. The configuration
187            information is used only to set up the replication connection and is stored
188            by MySQL in a file named master.info in the data directory.
189          returned: success
190          type: complex
191          contains:
192            caCertificate:
193              description:
194              - PEM representation of the trusted CA's x509 certificate.
195              returned: success
196              type: str
197            clientCertificate:
198              description:
199              - PEM representation of the slave's x509 certificate .
200              returned: success
201              type: str
202            clientKey:
203              description:
204              - PEM representation of the slave's private key. The corresponding public
205                key is encoded in the client's certificate.
206              returned: success
207              type: str
208            connectRetryInterval:
209              description:
210              - Seconds to wait between connect retries. MySQL's default is 60 seconds.
211              returned: success
212              type: int
213            dumpFilePath:
214              description:
215              - Path to a SQL dump file in Google Cloud Storage from which the slave
216                instance is to be created. The URI is in the form gs://bucketName/fileName.
217                Compressed gzip files (.gz) are also supported. Dumps should have
218                the binlog coordinates from which replication should begin. This can
219                be accomplished by setting --master-data to 1 when using mysqldump.
220              returned: success
221              type: str
222            masterHeartbeatPeriod:
223              description:
224              - Interval in milliseconds between replication heartbeats.
225              returned: success
226              type: int
227            password:
228              description:
229              - The password for the replication connection.
230              returned: success
231              type: str
232            sslCipher:
233              description:
234              - A list of permissible ciphers to use for SSL encryption.
235              returned: success
236              type: str
237            username:
238              description:
239              - The username for the replication connection.
240              returned: success
241              type: str
242            verifyServerCertificate:
243              description:
244              - Whether or not to check the master's Common Name value in the certificate
245                that it sends during the SSL handshake.
246              returned: success
247              type: bool
248        replicaNames:
249          description:
250          - The replicas of the instance.
251          returned: success
252          type: list
253        serviceAccountEmailAddress:
254          description:
255          - The service account email address assigned to the instance. This property
256            is applicable only to Second Generation instances.
257          returned: success
258          type: str
259    settings:
260      description:
261      - The user settings.
262      returned: success
263      type: complex
264      contains:
265        databaseFlags:
266          description:
267          - The database flags passed to the instance at startup.
268          returned: success
269          type: complex
270          contains:
271            name:
272              description:
273              - The name of the flag. These flags are passed at instance startup,
274                so include both server options and system variables for MySQL. Flags
275                should be specified with underscores, not hyphens.
276              returned: success
277              type: str
278            value:
279              description:
280              - The value of the flag. Booleans should be set to on for true and off
281                for false. This field must be omitted if the flag doesn't take a value.
282              returned: success
283              type: str
284        ipConfiguration:
285          description:
286          - The settings for IP Management. This allows to enable or disable the instance
287            IP and manage which external networks can connect to the instance. The
288            IPv4 address cannot be disabled for Second Generation instances.
289          returned: success
290          type: complex
291          contains:
292            ipv4Enabled:
293              description:
294              - Whether the instance should be assigned an IP address or not.
295              returned: success
296              type: bool
297            authorizedNetworks:
298              description:
299              - The list of external networks that are allowed to connect to the instance
300                using the IP. In CIDR notation, also known as 'slash' notation (e.g.
301                192.168.100.0/24).
302              returned: success
303              type: complex
304              contains:
305                expirationTime:
306                  description:
307                  - The time when this access control entry expires in RFC 3339 format,
308                    for example 2012-11-15T16:19:00.094Z.
309                  returned: success
310                  type: str
311                name:
312                  description:
313                  - An optional label to identify this entry.
314                  returned: success
315                  type: str
316                value:
317                  description:
318                  - The whitelisted value for the access control list. For example,
319                    to grant access to a client from an external IP (IPv4 or IPv6)
320                    address or subnet, use that address or subnet here.
321                  returned: success
322                  type: str
323            requireSsl:
324              description:
325              - Whether the mysqld should default to 'REQUIRE X509' for users connecting
326                over IP.
327              returned: success
328              type: bool
329        tier:
330          description:
331          - The tier or machine type for this instance, for example db-n1-standard-1.
332            For MySQL instances, this field determines whether the instance is Second
333            Generation (recommended) or First Generation.
334          returned: success
335          type: str
336        availabilityType:
337          description:
338          - The availabilityType define if your postgres instance is run zonal or
339            regional.
340          returned: success
341          type: str
342        backupConfiguration:
343          description:
344          - The daily backup configuration for the instance.
345          returned: success
346          type: complex
347          contains:
348            enabled:
349              description:
350              - Enable Autobackup for your instance.
351              returned: success
352              type: bool
353            binaryLogEnabled:
354              description:
355              - Whether binary log is enabled. If backup configuration is disabled,
356                binary log must be disabled as well. MySQL only.
357              returned: success
358              type: bool
359            startTime:
360              description:
361              - Define the backup start time in UTC (HH:MM) .
362              returned: success
363              type: str
364        settingsVersion:
365          description:
366          - The version of instance settings. This is a required field for update
367            method to make sure concurrent updates are handled properly. During update,
368            use the most recent settingsVersion value for this instance and do not
369            try to update this value.
370          returned: success
371          type: int
372'''
373
374################################################################################
375# Imports
376################################################################################
377from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
378import json
379
380################################################################################
381# Main
382################################################################################
383
384
385def main():
386    module = GcpModule(argument_spec=dict())
387
388    if module._name == 'gcp_sql_instance_facts':
389        module.deprecate("The 'gcp_sql_instance_facts' module has been renamed to 'gcp_sql_instance_info'", version='2.13')
390
391    if not module.params['scopes']:
392        module.params['scopes'] = ['https://www.googleapis.com/auth/sqlservice.admin']
393
394    return_value = {'resources': fetch_list(module, collection(module))}
395    module.exit_json(**return_value)
396
397
398def collection(module):
399    return "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances".format(**module.params)
400
401
402def fetch_list(module, link):
403    auth = GcpSession(module, 'sql')
404    return auth.list(link, return_if_object, array_name='items')
405
406
407def return_if_object(module, response):
408    # If not found, return nothing.
409    if response.status_code == 404:
410        return None
411
412    # If no content, return nothing.
413    if response.status_code == 204:
414        return None
415
416    try:
417        module.raise_for_status(response)
418        result = response.json()
419    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
420        module.fail_json(msg="Invalid JSON response with error: %s" % inst)
421
422    if navigate_hash(result, ['error', 'errors']):
423        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
424
425    return result
426
427
428if __name__ == "__main__":
429    main()
430