summaryrefslogtreecommitdiffstats
path: root/ansible_collections/amazon/aws/plugins/modules/rds_snapshot_info.py
blob: 9617c5ad8fc4f6a416f50ecae9afd730dce4959c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2014-2017 Ansible Project
# Copyright (c) 2017, 2018 Will Thames
# Copyright (c) 2017, 2018 Michael De La Rue
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

DOCUMENTATION = r"""
---
module: rds_snapshot_info
version_added: 5.0.0
short_description: obtain information about one or more RDS snapshots
description:
  - Obtain information about one or more RDS snapshots. These can be for unclustered snapshots or snapshots of clustered DBs (Aurora).
  - Aurora snapshot information may be obtained if no identifier parameters are passed or if one of the cluster parameters are passed.
  - This module was originally added to C(community.aws) in release 1.0.0.
options:
  db_snapshot_identifier:
    description:
      - Name of an RDS (unclustered) snapshot.
      - Mutually exclusive with I(db_instance_identifier), I(db_cluster_identifier), I(db_cluster_snapshot_identifier)
    required: false
    aliases:
      - snapshot_name
    type: str
  db_instance_identifier:
    description:
      - RDS instance name for which to find snapshots.
      - Mutually exclusive with I(db_snapshot_identifier), I(db_cluster_identifier), I(db_cluster_snapshot_identifier)
    required: false
    type: str
  db_cluster_identifier:
    description:
      - RDS cluster name for which to find snapshots.
      - Mutually exclusive with I(db_snapshot_identifier), I(db_instance_identifier), I(db_cluster_snapshot_identifier)
    required: false
    type: str
  db_cluster_snapshot_identifier:
    description:
      - Name of an RDS cluster snapshot.
      - Mutually exclusive with I(db_instance_identifier), I(db_snapshot_identifier), I(db_cluster_identifier)
    required: false
    type: str
  snapshot_type:
    description:
      - Type of snapshot to find.
      - By default both automated and manual snapshots will be returned.
    required: false
    choices: ['automated', 'manual', 'shared', 'public']
    type: str
author:
  - "Will Thames (@willthames)"
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
"""

EXAMPLES = r"""
- name: Get information about an snapshot
  amazon.aws.rds_snapshot_info:
    db_snapshot_identifier: snapshot_name
  register: new_database_info

- name: Get all RDS snapshots for an RDS instance
  amazon.aws.rds_snapshot_info:
    db_instance_identifier: helloworld-rds-master
"""

RETURN = r"""
snapshots:
  description: List of non-clustered snapshots
  returned: When cluster parameters are not passed
  type: complex
  contains:
    allocated_storage:
      description: How many gigabytes of storage are allocated
      returned: always
      type: int
      sample: 10
    availability_zone:
      description: The availability zone of the database from which the snapshot was taken
      returned: always
      type: str
      sample: us-west-2b
    db_instance_identifier:
      description: Database instance identifier
      returned: always
      type: str
      sample: hello-world-rds
    db_snapshot_arn:
      description: Snapshot ARN
      returned: always
      type: str
      sample: arn:aws:rds:us-west-2:123456789012:snapshot:rds:hello-world-rds-us1-2018-05-16-04-03
    db_snapshot_identifier:
      description: Snapshot name
      returned: always
      type: str
      sample: rds:hello-world-rds-us1-2018-05-16-04-03
    encrypted:
      description: Whether the snapshot was encrypted
      returned: always
      type: bool
      sample: true
    engine:
      description: Database engine
      returned: always
      type: str
      sample: postgres
    engine_version:
      description: Database engine version
      returned: always
      type: str
      sample: 9.5.10
    iam_database_authentication_enabled:
      description: Whether database authentication through IAM is enabled
      returned: always
      type: bool
      sample: false
    instance_create_time:
      description: Time the Instance was created
      returned: always
      type: str
      sample: '2017-10-10T04:00:07.434000+00:00'
    kms_key_id:
      description: ID of the KMS Key encrypting the snapshot
      returned: always
      type: str
      sample: arn:aws:kms:us-west-2:123456789012:key/abcd1234-1234-aaaa-0000-1234567890ab
    license_model:
      description: License model
      returned: always
      type: str
      sample: postgresql-license
    master_username:
      description: Database master username
      returned: always
      type: str
      sample: dbadmin
    option_group_name:
      description: Database option group name
      returned: always
      type: str
      sample: default:postgres-9-5
    percent_progress:
      description: Percent progress of snapshot
      returned: always
      type: int
      sample: 100
    snapshot_create_time:
      description: Time snapshot was created
      returned: always
      type: str
      sample: '2018-05-16T04:03:33.871000+00:00'
    snapshot_type:
      description: Type of snapshot
      returned: always
      type: str
      sample: automated
    status:
      description: Status of snapshot
      returned: always
      type: str
      sample: available
    storage_type:
      description: Storage type of underlying DB
      returned: always
      type: str
      sample: gp2
    tags:
      description: Snapshot tags
      returned: when snapshot is not shared
      type: complex
      contains: {}
    vpc_id:
      description: ID of VPC containing the DB
      returned: always
      type: str
      sample: vpc-abcd1234
cluster_snapshots:
  description: List of cluster snapshots
  returned: always
  type: complex
  contains:
    allocated_storage:
      description: How many gigabytes of storage are allocated
      returned: always
      type: int
      sample: 1
    availability_zones:
      description: The availability zones of the database from which the snapshot was taken
      returned: always
      type: list
      sample:
      - ca-central-1a
      - ca-central-1b
    cluster_create_time:
      description: Date and time the cluster was created
      returned: always
      type: str
      sample: '2018-05-17T00:13:40.223000+00:00'
    db_cluster_identifier:
      description: Database cluster identifier
      returned: always
      type: str
      sample: test-aurora-cluster
    db_cluster_snapshot_arn:
      description: ARN of the database snapshot
      returned: always
      type: str
      sample: arn:aws:rds:ca-central-1:123456789012:cluster-snapshot:test-aurora-snapshot
    db_cluster_snapshot_identifier:
      description: Snapshot identifier
      returned: always
      type: str
      sample: test-aurora-snapshot
    engine:
      description: Database engine
      returned: always
      type: str
      sample: aurora
    engine_version:
      description: Database engine version
      returned: always
      type: str
      sample: 5.6.10a
    iam_database_authentication_enabled:
      description: Whether database authentication through IAM is enabled
      returned: always
      type: bool
      sample: false
    kms_key_id:
      description: ID of the KMS Key encrypting the snapshot
      returned: always
      type: str
      sample: arn:aws:kms:ca-central-1:123456789012:key/abcd1234-abcd-1111-aaaa-0123456789ab
    license_model:
      description: License model
      returned: always
      type: str
      sample: aurora
    master_username:
      description: Database master username
      returned: always
      type: str
      sample: shertel
    percent_progress:
      description: Percent progress of snapshot
      returned: always
      type: int
      sample: 0
    port:
      description: Database port
      returned: always
      type: int
      sample: 0
    snapshot_create_time:
      description: Date and time when the snapshot was created
      returned: always
      type: str
      sample: '2018-05-17T00:23:23.731000+00:00'
    snapshot_type:
      description: Type of snapshot
      returned: always
      type: str
      sample: manual
    status:
      description: Status of snapshot
      returned: always
      type: str
      sample: creating
    storage_encrypted:
      description: Whether the snapshot is encrypted
      returned: always
      type: bool
      sample: true
    tags:
      description: Tags of the snapshot
      returned: when snapshot is not shared
      type: complex
      contains: {}
    vpc_id:
      description: VPC of the database
      returned: always
      type: str
      sample: vpc-abcd1234
"""

from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict

from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict

try:
    import botocore
except ImportError:
    pass  # caught by AnsibleAWSModule


def common_snapshot_info(module, conn, method, prefix, params):
    paginator = conn.get_paginator(method)
    try:
        results = paginator.paginate(**params).build_full_result()[f"{prefix}s"]
    except is_boto3_error_code(f"{prefix}NotFound"):
        results = []
    except (
        botocore.exceptions.ClientError,
        botocore.exceptions.BotoCoreError,
    ) as e:  # pylint: disable=duplicate-except
        module.fail_json_aws(e, "trying to get snapshot information")

    for snapshot in results:
        try:
            if snapshot["SnapshotType"] != "shared":
                snapshot["Tags"] = boto3_tag_list_to_ansible_dict(
                    conn.list_tags_for_resource(ResourceName=snapshot[f"{prefix}Arn"], aws_retry=True)["TagList"]
                )
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            snapshot_name = snapshot[f"{prefix}Identifier"]
            module.fail_json_aws(e, f"Couldn't get tags for snapshot {snapshot_name}")

    return [camel_dict_to_snake_dict(snapshot, ignore_list=["Tags"]) for snapshot in results]


def cluster_snapshot_info(module, conn):
    snapshot_name = module.params.get("db_cluster_snapshot_identifier")
    snapshot_type = module.params.get("snapshot_type")
    instance_name = module.params.get("db_cluster_identifier")

    params = dict()
    if snapshot_name:
        params["DBClusterSnapshotIdentifier"] = snapshot_name
    if instance_name:
        params["DBClusterIdentifier"] = instance_name
    if snapshot_type:
        params["SnapshotType"] = snapshot_type
        if snapshot_type == "public":
            params["IncludePublic"] = True
        elif snapshot_type == "shared":
            params["IncludeShared"] = True

    return common_snapshot_info(module, conn, "describe_db_cluster_snapshots", "DBClusterSnapshot", params)


def standalone_snapshot_info(module, conn):
    snapshot_name = module.params.get("db_snapshot_identifier")
    snapshot_type = module.params.get("snapshot_type")
    instance_name = module.params.get("db_instance_identifier")

    params = dict()
    if snapshot_name:
        params["DBSnapshotIdentifier"] = snapshot_name
    if instance_name:
        params["DBInstanceIdentifier"] = instance_name
    if snapshot_type:
        params["SnapshotType"] = snapshot_type
        if snapshot_type == "public":
            params["IncludePublic"] = True
        elif snapshot_type == "shared":
            params["IncludeShared"] = True

    return common_snapshot_info(module, conn, "describe_db_snapshots", "DBSnapshot", params)


def main():
    argument_spec = dict(
        db_snapshot_identifier=dict(aliases=["snapshot_name"]),
        db_instance_identifier=dict(),
        db_cluster_identifier=dict(),
        db_cluster_snapshot_identifier=dict(),
        snapshot_type=dict(choices=["automated", "manual", "shared", "public"]),
    )

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        mutually_exclusive=[
            [
                "db_snapshot_identifier",
                "db_instance_identifier",
                "db_cluster_identifier",
                "db_cluster_snapshot_identifier",
            ]
        ],
    )

    conn = module.client("rds", retry_decorator=AWSRetry.jittered_backoff(retries=10))
    results = dict()
    if not module.params["db_cluster_identifier"] and not module.params["db_cluster_snapshot_identifier"]:
        results["snapshots"] = standalone_snapshot_info(module, conn)
    if not module.params["db_snapshot_identifier"] and not module.params["db_instance_identifier"]:
        results["cluster_snapshots"] = cluster_snapshot_info(module, conn)

    module.exit_json(changed=False, **results)


if __name__ == "__main__":
    main()