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
403
404
405
406
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Contributors to the Ansible project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
module: backup_selection
short_description: Create, delete and modify AWS Backup selection
version_added: 6.0.0
description:
- Manages AWS Backup selections.
- For more information see the AWS documentation for backup selections
U(https://docs.aws.amazon.com/aws-backup/latest/devguide/assigning-resources.html).
options:
backup_plan_name:
description:
- Uniquely identifies the backup plan to be associated with the selection of resources.
required: true
type: str
aliases:
- plan_name
backup_selection_name:
description:
- The display name of a resource selection document. Must contain 1 to 50 alphanumeric or '-_.' characters.
required: true
type: str
aliases:
- selection_name
iam_role_arn:
description:
- The ARN of the IAM role that Backup uses to authenticate when backing up the target resource.
type: str
resources:
description:
- A list of Amazon Resource Names (ARNs) to assign to a backup plan. The maximum number of ARNs is 500 without wildcards,
or 30 ARNs with wildcards. If you need to assign many resources to a backup plan, consider a different resource selection
strategy, such as assigning all resources of a resource type or refining your resource selection using tags.
type: list
elements: str
list_of_tags:
description:
- A list of conditions that you define to assign resources to your backup plans using tags.
- Condition operators are case sensitive.
- When you specify more than one condition in I(list_of_tags), you assign all resources that match AT LEAST ONE condition (using OR logic).
type: list
elements: dict
suboptions:
condition_type:
description:
- An operation applied to a key-value pair used to assign resources to your backup plan.
- Condition only supports C(STRINGEQUALS).
type: str
condition_key:
description:
- The key in a key-value pair.
type: str
condition_value:
description:
- The value in a key-value pair.
type: str
not_resources:
description:
- A list of Amazon Resource Names (ARNs) to exclude from a backup plan. The maximum number of ARNs is 500 without wildcards,
or 30 ARNs with wildcards. If you need to exclude many resources from a backup plan, consider a different resource
selection strategy, such as assigning only one or a few resource types or refining your resource selection using tags.
type: list
elements: str
conditions:
description:
- A list of conditions (expressed as a dict) that you define to assign resources to your backup plans using tags.
- When you specify more than one condition in I(conditions), you only assign the resources that match ALL conditions (using AND logic).
- I(conditions) supports C(string_equals), C(string_like), C(string_not_equals), and C(string_not_like). I(list_of_tags) only supports C(string_equals).
type: dict
suboptions:
string_equals:
description:
- Filters the values of your tagged resources for only those resources that you tagged with the same value.
type: list
default: []
elements: dict
suboptions:
condition_key:
description:
- The key in a key-value pair.
- I(condition_key) in the I(conditions) option must use the AWS resource tag prefix, e.g. 'aws:ResourceTag/key-name'
type: str
condition_value:
description: The value in a key-value pair.
type: str
string_like:
description:
- Filters the values of your tagged resources for matching tag values with the use of a wildcard character (*) anywhere in the string.
For example, "prod*" or "*rod*" matches the tag value "production".
type: list
default: []
elements: dict
suboptions:
condition_key:
description:
- The key in a key-value pair.
- I(condition_key) in the I(conditions) option must use the AWS resource tag prefix, e.g. 'aws:ResourceTag/key-name'
type: str
condition_value:
description: The value in a key-value pair.
type: str
string_not_equals:
description:
- Filters the values of your tagged resources for only those resources that you tagged that do not have the same value.
type: list
default: []
elements: dict
suboptions:
condition_key:
description:
- The key in a key-value pair.
- I(condition_key) in the I(conditions) option must use the AWS resource tag prefix, e.g. 'aws:ResourceTag/key-name'
type: str
condition_value:
description: The value in a key-value pair.
type: str
string_not_like:
description:
- Filters the values of your tagged resources for non-matching tag values with the use of a wildcard character (*) anywhere in the string.
type: list
default: []
elements: dict
suboptions:
condition_key:
description:
- The key in a key-value pair.
- I(condition_key) in the I(conditions) option must use the AWS resource tag prefix, e.g. 'aws:ResourceTag/key-name'
type: str
condition_value:
description: The value in a key-value pair.
type: str
state:
description:
- Create, delete a backup selection.
default: present
choices: ['present', 'absent']
type: str
author:
- Kristof Imre Szabo (@krisek)
- Alina Buzachis (@alinabuzachis)
extends_documentation_fragment:
- amazon.aws.common.modules
- amazon.aws.region.modules
- amazon.aws.boto3
"""
EXAMPLES = r"""
- name: Create backup selection
amazon.aws.backup_selection:
selection_name: elastic
backup_plan_name: 1111f877-1ecf-4d79-9718-a861cd09df3b
iam_role_arn: arn:aws:iam::111122223333:role/system-backup
resources:
- arn:aws:elasticfilesystem:*:*:file-system/*
"""
RETURN = r"""
backup_selection:
description: Backup selection details.
returned: always
type: complex
contains:
backup_plan_id:
description: Backup plan id.
returned: always
type: str
sample: "1111f877-1ecf-4d79-9718-a861cd09df3b"
creation_date:
description: Backup plan creation date.
returned: always
type: str
sample: "2023-01-24T10:08:03.193000+01:00"
iam_role_arn:
description: The ARN of the IAM role that Backup uses.
returned: always
type: str
sample: "arn:aws:iam::111122223333:role/system-backup"
selection_id:
description: Backup selection id.
returned: always
type: str
sample: "1111c217-5d71-4a55-8728-5fc4e63d437b"
selection_name:
description: Backup selection name.
returned: always
type: str
sample: elastic
conditions:
description: List of conditions (expressed as a dict) that are defined to assign resources to the backup plan using tags.
returned: always
type: dict
sample: {}
list_of_tags:
description: Conditions defined to assign resources to the backup plans using tags.
returned: always
type: list
elements: dict
sample: []
not_resources:
description: List of Amazon Resource Names (ARNs) that are excluded from the backup plan.
returned: always
type: list
sample: []
resources:
description: List of Amazon Resource Names (ARNs) that are assigned to the backup plan.
returned: always
type: list
sample: []
"""
import json
try:
import botocore
except ImportError:
pass # Handled by AnsibleAWSModule
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
from ansible_collections.amazon.aws.plugins.module_utils.backup import get_plan_details
from ansible_collections.amazon.aws.plugins.module_utils.backup import get_selection_details
from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry
def check_for_update(current_selection, backup_selection_data, iam_role_arn):
update_needed = False
if current_selection[0].get("IamRoleArn", None) != iam_role_arn:
update_needed = True
fields_to_check = ["Resources", "ListOfTags", "NotResources", "Conditions"]
for field_name in fields_to_check:
field_value_from_aws = json.dumps(current_selection[0].get(field_name, []), sort_keys=True)
new_field_value = json.dumps(backup_selection_data.get(field_name, []), sort_keys=True)
if new_field_value != field_value_from_aws:
if field_name != "Conditions":
update_needed = True
elif not ( # Check that Conditions values are not both empty
field_value_from_aws
== '{"StringEquals": [], "StringLike": [], "StringNotEquals": [], "StringNotLike": []}' # Default AWS Conditions return value
and new_field_value == "[]"
):
update_needed = True
return update_needed
def main():
argument_spec = dict(
backup_selection_name=dict(type="str", required=True, aliases=["selection_name"]),
backup_plan_name=dict(type="str", required=True, aliases=["plan_name"]),
iam_role_arn=dict(type="str"),
resources=dict(type="list", elements="str"),
conditions=dict(
type="dict",
options=dict(
string_equals=dict(
type="list",
default=[],
elements="dict",
options=dict(
condition_key=dict(type="str", no_log=False),
condition_value=dict(type="str"),
),
),
string_like=dict(
type="list",
default=[],
elements="dict",
options=dict(
condition_key=dict(type="str", no_log=False),
condition_value=dict(type="str"),
),
),
string_not_equals=dict(
type="list",
default=[],
elements="dict",
options=dict(
condition_key=dict(type="str", no_log=False),
condition_value=dict(type="str"),
),
),
string_not_like=dict(
type="list",
default=[],
elements="dict",
options=dict(
condition_key=dict(type="str", no_log=False),
condition_value=dict(type="str"),
),
),
),
),
not_resources=dict(type="list", elements="str"),
list_of_tags=dict(
type="list",
elements="dict",
options=dict(
condition_type=dict(type="str"),
condition_key=dict(type="str", no_log=False),
condition_value=dict(type="str"),
),
),
state=dict(default="present", choices=["present", "absent"]),
)
required_if = [
("state", "present", ["backup_selection_name", "backup_plan_name", "iam_role_arn"]),
("state", "absent", ["backup_selection_name", "backup_plan_name"]),
]
module = AnsibleAWSModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True)
state = module.params.get("state")
backup_selection_name = module.params.get("selection_name")
backup_plan_name = module.params.get("backup_plan_name")
iam_role_arn = module.params.get("iam_role_arn")
resources = module.params.get("resources")
list_of_tags = module.params.get("list_of_tags")
not_resources = module.params.get("not_resources")
conditions = module.params.get("conditions")
try:
client = module.client("backup", retry_decorator=AWSRetry.jittered_backoff())
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to connect to AWS")
results = {"changed": False, "exists": False, "backup_selection": {}}
current_selection = get_selection_details(module, client, backup_plan_name, backup_selection_name)
results["current_selection"] = current_selection
if state == "present":
# build data specified by user
update_needed = False
backup_selection_data = {"SelectionName": backup_selection_name, "IamRoleArn": iam_role_arn}
if resources:
backup_selection_data["Resources"] = resources
if list_of_tags:
backup_selection_data["ListOfTags"] = snake_dict_to_camel_dict(list_of_tags, capitalize_first=True)
if not_resources:
backup_selection_data["NotResources"] = not_resources
if conditions:
backup_selection_data["Conditions"] = snake_dict_to_camel_dict(conditions, capitalize_first=True)
if current_selection:
results["exists"] = True
update_needed = check_for_update(current_selection, backup_selection_data, iam_role_arn)
if update_needed:
if module.check_mode:
results["changed"] = True
module.exit_json(**results, msg="Would have created selection if not in check mode")
try:
client.delete_backup_selection(
aws_retry=True,
SelectionId=current_selection[0]["SelectionId"],
BackupPlanId=current_selection[0]["BackupPlanId"],
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to delete selection")
elif not update_needed:
results["exists"] = True
# state is present but backup vault doesnt exist
if not current_selection or update_needed:
results["changed"] = True
results["exists"] = True
plan = get_plan_details(module, client, backup_plan_name)
if module.check_mode:
module.exit_json(**results, msg="Would have created selection if not in check mode")
try:
client.create_backup_selection(
BackupSelection=backup_selection_data, BackupPlanId=plan[0]["backup_plan_id"]
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to create selection")
new_selection = get_selection_details(module, client, backup_plan_name, backup_selection_name)
results["backup_selection"] = camel_dict_to_snake_dict(*new_selection)
elif state == "absent":
if current_selection:
results["changed"] = True
if module.check_mode:
module.exit_json(**results, msg="Would have deleted backup selection if not in check mode")
try:
client.delete_backup_selection(
aws_retry=True,
SelectionId=current_selection[0]["SelectionId"],
BackupPlanId=current_selection[0]["BackupPlanId"],
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to delete selection")
module.exit_json(**results)
if __name__ == "__main__":
main()
|