Debian Codegraph @

ansible_collections/community/aws/plugins/modules/secretsmanager_secret.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, REY Remi
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: secretsmanager_secret
10 version_added: 1.0.0
11 short_description: Manage secrets stored in AWS Secrets Manager
12 description:
13 - Create, update, and delete secrets stored in AWS Secrets Manager.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_secret).
15 The usage did not change.
16 author:
17 - "REY Remi (@rrey)"
18 options:
19 name:
20 description:
21 - Friendly name for the secret you are creating.
22 required: true
23 type: str
24 state:
25 description:
26 - Whether the secret should be exist or not.
27 default: 'present'
28 choices: ['present', 'absent']
29 type: str
30 overwrite:
31 description:
32 - Whether to overwrite an existing secret with the same name.
33 - If set to C(True), an existing secret with the same I(name) will be overwritten.
34 - If set to C(False), a secret with the given I(name) will only be created if none exists.
35 type: bool
36 default: True
37 version_added: 5.3.0
38 recovery_window:
39 description:
40 - Only used if state is absent.
41 - Specifies the number of days that Secrets Manager waits before it can delete the secret.
42 - If set to 0, the deletion is forced without recovery.
43 default: 30
44 type: int
45 description:
46 description:
47 - Specifies a user-provided description of the secret.
48 type: str
49 default: ''
50 replica:
51 description:
52 - Specifies a list of regions and kms_key_ids (optional) to replicate the secret to
53 type: list
54 elements: dict
55 version_added: 5.3.0
56 suboptions:
57 region:
58 description:
59 - Region to replicate secret to.
60 type: str
61 required: true
62 kms_key_id:
63 description:
64 - Specifies the ARN or alias of the AWS KMS customer master key (CMK) in the
65 destination region to be used (alias/aws/secretsmanager is assumed if not specified)
66 type: str
67 required: false
68 kms_key_id:
69 description:
70 - Specifies the ARN or alias of the AWS KMS customer master key (CMK) to be
71 used to encrypt the I(secret) values in the versions stored in this secret.
72 type: str
73 secret_type:
74 description:
75 - Specifies the type of data that you want to encrypt.
76 choices: ['binary', 'string']
77 default: 'string'
78 type: str
79 secret:
80 description:
81 - Specifies string or binary data that you want to encrypt and store in the new version of the secret.
82 - Mutually exclusive with the I(json_secret) option.
83 default: ""
84 type: str
85 json_secret:
86 description:
87 - Specifies JSON-formatted data that you want to encrypt and store in the new version of the
88 secret.
89 - Mutually exclusive with the I(secret) option.
90 type: json
91 version_added: 4.1.0
92 resource_policy:
93 description:
94 - Specifies JSON-formatted resource policy to attach to the secret. Useful when granting cross-account access
95 to secrets.
96 required: false
97 type: json
98 version_added: 3.1.0
99 rotation_lambda:
100 description:
101 - Specifies the ARN of the Lambda function that can rotate the secret.
102 type: str
103 rotation_interval:
104 description:
105 - Specifies the number of days between automatic scheduled rotations of the secret.
106 default: 30
107 type: int
108 notes:
109 - Support for I(purge_tags) was added in release 4.0.0.
110 extends_documentation_fragment:
111 - amazon.aws.region.modules
112 - amazon.aws.common.modules
113 - amazon.aws.tags
114 - amazon.aws.boto3
115 """
116
117 EXAMPLES = r"""
118 - name: Add string to AWS Secrets Manager
119 community.aws.secretsmanager_secret:
120 name: 'test_secret_string'
121 state: present
122 secret_type: 'string'
123 secret: "{{ super_secret_string }}"
124
125 - name: Add a secret with resource policy attached
126 community.aws.secretsmanager_secret:
127 name: 'test_secret_string'
128 state: present
129 secret_type: 'string'
130 secret: "{{ super_secret_string }}"
131 resource_policy: "{{ lookup('template', 'templates/resource_policy.json.j2', convert_data=False) | string }}"
132
133 - name: remove string from AWS Secrets Manager
134 community.aws.secretsmanager_secret:
135 name: 'test_secret_string'
136 state: absent
137 secret_type: 'string'
138 secret: "{{ super_secret_string }}"
139
140 - name: Only create a new secret, but do not update if alredy exists by name
141 community.aws.secretsmanager_secret:
142 name: 'random_string'
143 state: present
144 secret_type: 'string'
145 secret: "{{ lookup('community.general.random_string', length=16, special=false) }}"
146 overwrite: false
147 """
148
149 RETURN = r"""
150 secret:
151 description: The secret information
152 returned: always
153 type: complex
154 contains:
155 arn:
156 description: The ARN of the secret.
157 returned: always
158 type: str
159 sample: arn:aws:secretsmanager:eu-west-1:xxxxxxxxxx:secret:xxxxxxxxxxx
160 description:
161 description: A description of the secret.
162 returned: when the secret has a description
163 type: str
164 sample: An example description
165 last_accessed_date:
166 description: The date the secret was last accessed.
167 returned: always
168 type: str
169 sample: '2018-11-20T01:00:00+01:00'
170 last_changed_date:
171 description: The date the secret was last modified.
172 returned: always
173 type: str
174 sample: '2018-11-20T12:16:38.433000+01:00'
175 name:
176 description: The secret name.
177 returned: always
178 type: str
179 sample: my_secret
180 rotation_enabled:
181 description: The secret rotation status.
182 returned: always
183 type: bool
184 sample: false
185 version_ids_to_stages:
186 description: Provide the secret version ids and the associated secret stage.
187 returned: always
188 type: dict
189 sample: { "dc1ed59b-6d8e-4450-8b41-536dfe4600a9": [ "AWSCURRENT" ] }
190 tags:
191 description:
192 - A list of dictionaries representing the tags associated with the secret in the standard boto3 format.
193 returned: when the secret has tags
194 type: list
195 elements: dict
196 contains:
197 key:
198 description: The name or key of the tag.
199 type: str
200 example: MyTag
201 returned: success
202 value:
203 description: The value of the tag.
204 type: str
205 example: Some value.
206 returned: success
207 tags_dict:
208 description: A dictionary representing the tags associated with the secret.
209 type: dict
210 returned: when the secret has tags
211 example: {'MyTagName': 'Some Value'}
212 version_added: 4.0.0
213 """
214
215 import json
216 from traceback import format_exc
217
218 try:
219 from botocore.exceptions import BotoCoreError
220 from botocore.exceptions import ClientError
221 except ImportError:
222 pass # handled by AnsibleAWSModule
223
224 from ansible.module_utils._text import to_bytes
225 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
226 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
227
228 from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies
229 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
230 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
231 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
232
233 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
234
235
236 class Secret(object):
237 """An object representation of the Secret described by the self.module args"""
238
239 def __init__(
240 self,
241 name,
242 secret_type,
243 secret,
244 resource_policy=None,
245 description="",
246 kms_key_id=None,
247 tags=None,
248 lambda_arn=None,
249 rotation_interval=None,
250 replica_regions=None,
251 ):
252 self.name = name
253 self.description = description
254 self.replica_regions = replica_regions
255 self.kms_key_id = kms_key_id
256 if secret_type == "binary":
257 self.secret_type = "SecretBinary"
258 else:
259 self.secret_type = "SecretString"
260 self.secret = secret
261 self.resource_policy = resource_policy
262 self.tags = tags or {}
263 self.rotation_enabled = False
264 if lambda_arn:
265 self.rotation_enabled = True
266 self.rotation_lambda_arn = lambda_arn
267 self.rotation_rules = {"AutomaticallyAfterDays": int(rotation_interval)}
268
269 @property
270 def create_args(self):
271 args = {"Name": self.name}
272 if self.description:
273 args["Description"] = self.description
274 if self.kms_key_id:
275 args["KmsKeyId"] = self.kms_key_id
276 if self.replica_regions:
277 add_replica_regions = []
278 for replica in self.replica_regions:
279 if replica["kms_key_id"]:
280 add_replica_regions.append({"Region": replica["region"], "KmsKeyId": replica["kms_key_id"]})
281 else:
282 add_replica_regions.append({"Region": replica["region"]})
283 args["AddReplicaRegions"] = add_replica_regions
284 if self.tags:
285 args["Tags"] = ansible_dict_to_boto3_tag_list(self.tags)
286 args[self.secret_type] = self.secret
287 return args
288
289 @property
290 def update_args(self):
291 args = {"SecretId": self.name}
292 if self.description:
293 args["Description"] = self.description
294 if self.kms_key_id:
295 args["KmsKeyId"] = self.kms_key_id
296 args[self.secret_type] = self.secret
297 return args
298
299 @property
300 def secret_resource_policy_args(self):
301 args = {"SecretId": self.name}
302 if self.resource_policy:
303 args["ResourcePolicy"] = self.resource_policy
304 return args
305
306 @property
307 def boto3_tags(self):
308 return ansible_dict_to_boto3_tag_list(self.Tags)
309
310 def as_dict(self):
311 result = self.__dict__
312 result.pop("tags")
313 return snake_dict_to_camel_dict(result)
314
315
316 class SecretsManagerInterface(object):
317 """An interface with SecretsManager"""
318
319 def __init__(self, module):
320 self.module = module
321 self.client = self.module.client("secretsmanager")
322
323 def get_secret(self, name):
324 try:
325 secret = self.client.describe_secret(SecretId=name)
326 except self.client.exceptions.ResourceNotFoundException:
327 secret = None
328 except Exception as e:
329 self.module.fail_json_aws(e, msg="Failed to describe secret")
330 return secret
331
332 def get_resource_policy(self, name):
333 try:
334 resource_policy = self.client.get_resource_policy(SecretId=name)
335 except self.client.exceptions.ResourceNotFoundException:
336 resource_policy = None
337 except (BotoCoreError, ClientError) as e:
338 self.module.fail_json_aws(e, msg="Failed to get secret resource policy")
339 return resource_policy
340
341 def create_secret(self, secret):
342 if self.module.check_mode:
343 self.module.exit_json(changed=True)
344 try:
345 created_secret = self.client.create_secret(**secret.create_args)
346 except (BotoCoreError, ClientError) as e:
347 self.module.fail_json_aws(e, msg="Failed to create secret")
348
349 if secret.rotation_enabled:
350 response = self.update_rotation(secret)
351 created_secret["VersionId"] = response.get("VersionId")
352 return created_secret
353
354 def update_secret(self, secret):
355 if self.module.check_mode:
356 self.module.exit_json(changed=True)
357 try:
358 response = self.client.update_secret(**secret.update_args)
359 except (BotoCoreError, ClientError) as e:
360 self.module.fail_json_aws(e, msg="Failed to update secret")
361 return response
362
363 def put_resource_policy(self, secret):
364 if self.module.check_mode:
365 self.module.exit_json(changed=True)
366 try:
367 json.loads(secret.secret_resource_policy_args.get("ResourcePolicy"))
368 except (TypeError, ValueError) as e:
369 self.module.fail_json(msg=f"Failed to parse resource policy as JSON: {str(e)}", exception=format_exc())
370
371 try:
372 response = self.client.put_resource_policy(**secret.secret_resource_policy_args)
373 except (BotoCoreError, ClientError) as e:
374 self.module.fail_json_aws(e, msg="Failed to update secret resource policy")
375 return response
376
377 def remove_replication(self, name, regions):
378 if self.module.check_mode:
379 self.module.exit_json(changed=True)
380 try:
381 response = self.client.remove_regions_from_replication(SecretId=name, RemoveReplicaRegions=regions)
382 except (BotoCoreError, ClientError) as e:
383 self.module.fail_json_aws(e, msg="Failed to replicate secret")
384 return response
385
386 def replicate_secret(self, name, regions):
387 if self.module.check_mode:
388 self.module.exit_json(changed=True)
389 try:
390 replica_regions = []
391 for replica in regions:
392 if replica["kms_key_id"]:
393 replica_regions.append({"Region": replica["region"], "KmsKeyId": replica["kms_key_id"]})
394 else:
395 replica_regions.append({"Region": replica["region"]})
396 response = self.client.replicate_secret_to_regions(SecretId=name, AddReplicaRegions=replica_regions)
397 except (BotoCoreError, ClientError) as e:
398 self.module.fail_json_aws(e, msg="Failed to replicate secret")
399 return response
400
401 def restore_secret(self, name):
402 if self.module.check_mode:
403 self.module.exit_json(changed=True)
404 try:
405 response = self.client.restore_secret(SecretId=name)
406 except (BotoCoreError, ClientError) as e:
407 self.module.fail_json_aws(e, msg="Failed to restore secret")
408 return response
409
410 def delete_secret(self, name, recovery_window):
411 if self.module.check_mode:
412 self.module.exit_json(changed=True)
413 try:
414 if recovery_window == 0:
415 response = self.client.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)
416 else:
417 response = self.client.delete_secret(SecretId=name, RecoveryWindowInDays=recovery_window)
418 except (BotoCoreError, ClientError) as e:
419 self.module.fail_json_aws(e, msg="Failed to delete secret")
420 return response
421
422 def delete_resource_policy(self, name):
423 if self.module.check_mode:
424 self.module.exit_json(changed=True)
425 try:
426 response = self.client.delete_resource_policy(SecretId=name)
427 except (BotoCoreError, ClientError) as e:
428 self.module.fail_json_aws(e, msg="Failed to delete secret resource policy")
429 return response
430
431 def update_rotation(self, secret):
432 if secret.rotation_enabled:
433 try:
434 response = self.client.rotate_secret(
435 SecretId=secret.name,
436 RotationLambdaARN=secret.rotation_lambda_arn,
437 RotationRules=secret.rotation_rules,
438 )
439 except (BotoCoreError, ClientError) as e:
440 self.module.fail_json_aws(e, msg="Failed to rotate secret secret")
441 else:
442 try:
443 response = self.client.cancel_rotate_secret(SecretId=secret.name)
444 except (BotoCoreError, ClientError) as e:
445 self.module.fail_json_aws(e, msg="Failed to cancel rotation")
446 return response
447
448 def tag_secret(self, secret_name, tags):
449 if self.module.check_mode:
450 self.module.exit_json(changed=True)
451 try:
452 self.client.tag_resource(SecretId=secret_name, Tags=tags)
453 except (BotoCoreError, ClientError) as e:
454 self.module.fail_json_aws(e, msg="Failed to add tag(s) to secret")
455
456 def untag_secret(self, secret_name, tag_keys):
457 if self.module.check_mode:
458 self.module.exit_json(changed=True)
459 try:
460 self.client.untag_resource(SecretId=secret_name, TagKeys=tag_keys)
461 except (BotoCoreError, ClientError) as e:
462 self.module.fail_json_aws(e, msg="Failed to remove tag(s) from secret")
463
464 def secrets_match(self, desired_secret, current_secret):
465 """Compare secrets except tags and rotation
466
467 Args:
468 desired_secret: camel dict representation of the desired secret state.
469 current_secret: secret reference as returned by the secretsmanager api.
470
471 Returns: bool
472 """
473 if desired_secret.description != current_secret.get("Description", ""):
474 return False
475 if desired_secret.kms_key_id != current_secret.get("KmsKeyId"):
476 return False
477 current_secret_value = self.client.get_secret_value(SecretId=current_secret.get("Name"))
478 if desired_secret.secret_type == "SecretBinary":
479 desired_value = to_bytes(desired_secret.secret)
480 else:
481 desired_value = desired_secret.secret
482 if desired_value != current_secret_value.get(desired_secret.secret_type):
483 return False
484 return True
485
486
487 def rotation_match(desired_secret, current_secret):
488 """Compare secrets rotation configuration
489
490 Args:
491 desired_secret: camel dict representation of the desired secret state.
492 current_secret: secret reference as returned by the secretsmanager api.
493
494 Returns: bool
495 """
496 if desired_secret.rotation_enabled != current_secret.get("RotationEnabled", False):
497 return False
498 if desired_secret.rotation_enabled:
499 if desired_secret.rotation_lambda_arn != current_secret.get("RotationLambdaARN"):
500 return False
501 if desired_secret.rotation_rules != current_secret.get("RotationRules"):
502 return False
503 return True
504
505
506 def compare_regions(desired_secret, current_secret):
507 """Compare secrets replication configuration
508
509 Args:
510 desired_secret: camel dict representation of the desired secret state.
511 current_secret: secret reference as returned by the secretsmanager api.
512
513 Returns: bool
514 """
515 regions_to_set_replication = []
516 regions_to_remove_replication = []
517
518 if desired_secret.replica_regions is None:
519 return regions_to_set_replication, regions_to_remove_replication
520
521 if desired_secret.replica_regions:
522 regions_to_set_replication = desired_secret.replica_regions
523
524 for current_secret_region in current_secret.get("ReplicationStatus", []):
525 if regions_to_set_replication:
526 for desired_secret_region in regions_to_set_replication:
527 if current_secret_region["Region"] == desired_secret_region["region"]:
528 regions_to_set_replication.remove(desired_secret_region)
529 else:
530 regions_to_remove_replication.append(current_secret_region["Region"])
531 else:
532 regions_to_remove_replication.append(current_secret_region["Region"])
533
534 return regions_to_set_replication, regions_to_remove_replication
535
536
537 def main():
538 replica_args = dict(
539 region=dict(type="str", required=True),
540 kms_key_id=dict(type="str", required=False),
541 )
542
543 module = AnsibleAWSModule(
544 argument_spec={
545 "name": dict(required=True),
546 "state": dict(choices=["present", "absent"], default="present"),
547 "overwrite": dict(type="bool", default=True),
548 "description": dict(default=""),
549 "replica": dict(type="list", elements="dict", options=replica_args),
550 "kms_key_id": dict(),
551 "secret_type": dict(choices=["binary", "string"], default="string"),
552 "secret": dict(default="", no_log=True),
553 "json_secret": dict(type="json", no_log=True),
554 "resource_policy": dict(type="json", default=None),
555 "tags": dict(type="dict", default=None, aliases=["resource_tags"]),
556 "purge_tags": dict(type="bool", default=True),
557 "rotation_lambda": dict(),
558 "rotation_interval": dict(type="int", default=30),
559 "recovery_window": dict(type="int", default=30),
560 },
561 mutually_exclusive=[["secret", "json_secret"]],
562 supports_check_mode=True,
563 )
564
565 changed = False
566 state = module.params.get("state")
567 secrets_mgr = SecretsManagerInterface(module)
568 recovery_window = module.params.get("recovery_window")
569 secret = Secret(
570 module.params.get("name"),
571 module.params.get("secret_type"),
572 module.params.get("secret") or module.params.get("json_secret"),
573 description=module.params.get("description"),
574 replica_regions=module.params.get("replica"),
575 kms_key_id=module.params.get("kms_key_id"),
576 resource_policy=module.params.get("resource_policy"),
577 tags=module.params.get("tags"),
578 lambda_arn=module.params.get("rotation_lambda"),
579 rotation_interval=module.params.get("rotation_interval"),
580 )
581 purge_tags = module.params.get("purge_tags")
582
583 current_secret = secrets_mgr.get_secret(secret.name)
584
585 if state == "absent":
586 if current_secret:
587 if not current_secret.get("DeletedDate"):
588 result = camel_dict_to_snake_dict(
589 secrets_mgr.delete_secret(secret.name, recovery_window=recovery_window)
590 )
591 changed = True
592 elif current_secret.get("DeletedDate") and recovery_window == 0:
593 result = camel_dict_to_snake_dict(
594 secrets_mgr.delete_secret(secret.name, recovery_window=recovery_window)
595 )
596 changed = True
597 else:
598 result = "secret already scheduled for deletion"
599 else:
600 result = "secret does not exist"
601 if state == "present":
602 if current_secret is None:
603 result = secrets_mgr.create_secret(secret)
604 if secret.resource_policy and result.get("ARN"):
605 result = secrets_mgr.put_resource_policy(secret)
606 changed = True
607 else:
608 # current_secret exists; decide what to do with it
609 if current_secret.get("DeletedDate"):
610 secrets_mgr.restore_secret(secret.name)
611 changed = True
612 if not secrets_mgr.secrets_match(secret, current_secret):
613 overwrite = module.params.get("overwrite")
614 if overwrite:
615 result = secrets_mgr.update_secret(secret)
616 changed = True
617 if not rotation_match(secret, current_secret):
618 result = secrets_mgr.update_rotation(secret)
619 changed = True
620
621 current_resource_policy_response = secrets_mgr.get_resource_policy(secret.name)
622 current_resource_policy = current_resource_policy_response.get("ResourcePolicy")
623 if compare_policies(secret.resource_policy, current_resource_policy):
624 if secret.resource_policy is None and current_resource_policy:
625 result = secrets_mgr.delete_resource_policy(secret.name)
626 else:
627 result = secrets_mgr.put_resource_policy(secret)
628 changed = True
629
630 if module.params.get("tags") is not None:
631 current_tags = boto3_tag_list_to_ansible_dict(current_secret.get("Tags", []))
632 tags_to_add, tags_to_remove = compare_aws_tags(current_tags, secret.tags, purge_tags)
633 if tags_to_add:
634 secrets_mgr.tag_secret(secret.name, ansible_dict_to_boto3_tag_list(tags_to_add))
635 changed = True
636 if tags_to_remove:
637 secrets_mgr.untag_secret(secret.name, tags_to_remove)
638 changed = True
639
640 regions_to_set_replication, regions_to_remove_replication = compare_regions(secret, current_secret)
641 if regions_to_set_replication:
642 secrets_mgr.replicate_secret(secret.name, regions_to_set_replication)
643 changed = True
644 if regions_to_remove_replication:
645 secrets_mgr.remove_replication(secret.name, regions_to_remove_replication)
646 changed = True
647
648 result = camel_dict_to_snake_dict(secrets_mgr.get_secret(secret.name))
649 if result.get("tags", None) is not None:
650 result["tags_dict"] = boto3_tag_list_to_ansible_dict(result.get("tags", []))
651 result.pop("response_metadata")
652
653 module.exit_json(changed=changed, secret=result)
654
655
656 if __name__ == "__main__":
657 main()