Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Ansible Project
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: ssm_parameter
10 version_added: 1.0.0
11 short_description: Manage key-value pairs in AWS Systems Manager Parameter Store
12 description:
13 - Manage key-value pairs in AWS Systems Manager (SSM) Parameter Store.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_ssm_parameter_store).
15 The usage did not change.
16 options:
17 name:
18 description:
19 - Parameter key name.
20 required: true
21 type: str
22 description:
23 description:
24 - Parameter key description.
25 required: false
26 type: str
27 value:
28 description:
29 - Parameter value.
30 required: false
31 type: str
32 state:
33 description:
34 - Creates or modifies an existing parameter.
35 - Deletes a parameter.
36 required: false
37 choices: ['present', 'absent']
38 default: present
39 type: str
40 string_type:
41 description:
42 - Parameter String type.
43 required: false
44 choices: ['String', 'StringList', 'SecureString']
45 default: String
46 type: str
47 aliases: ['type']
48 decryption:
49 description:
50 - Work with SecureString type to get plain text secrets
51 type: bool
52 required: false
53 default: true
54 key_id:
55 description:
56 - AWS KMS key to decrypt the secrets.
57 - The default key (C(alias/aws/ssm)) is automatically generated the first
58 time it's requested.
59 required: false
60 default: alias/aws/ssm
61 type: str
62 overwrite_value:
63 description:
64 - Option to overwrite an existing value if it already exists.
65 required: false
66 choices: ['never', 'changed', 'always']
67 default: changed
68 type: str
69 tier:
70 description:
71 - Parameter store tier type.
72 required: false
73 choices: ['Standard', 'Advanced', 'Intelligent-Tiering']
74 default: Standard
75 type: str
76 version_added: 1.5.0
77 seealso:
78 - ref: amazon.aws.aws_ssm lookup <ansible_collections.amazon.aws.aws_ssm_lookup>
79 description: The documentation for the C(amazon.aws.aws_ssm) lookup plugin.
80
81 author:
82 - "Davinder Pal (@116davinder) <[email protected]>"
83 - "Nathan Webster (@nathanwebsterdotme)"
84 - "Bill Wang (@ozbillwang) <[email protected]>"
85 - "Michael De La Rue (@mikedlr)"
86
87 notes:
88 - Support for I(tags) and I(purge_tags) was added in release 5.3.0.
89
90 extends_documentation_fragment:
91 - amazon.aws.common.modules
92 - amazon.aws.region.modules
93 - amazon.aws.tags
94 - amazon.aws.boto3
95 """
96
97 EXAMPLES = r"""
98 - name: Create or update key/value pair in AWS SSM parameter store
99 community.aws.ssm_parameter:
100 name: "Hello"
101 description: "This is your first key"
102 value: "World"
103
104 - name: Delete the key
105 community.aws.ssm_parameter:
106 name: "Hello"
107 state: absent
108
109 - name: Create or update secure key/value pair with default KMS key (aws/ssm)
110 community.aws.ssm_parameter:
111 name: "Hello"
112 description: "This is your first key"
113 string_type: "SecureString"
114 value: "World"
115
116 - name: Create or update secure key/value pair with nominated KMS key
117 community.aws.ssm_parameter:
118 name: "Hello"
119 description: "This is your first key"
120 string_type: "SecureString"
121 key_id: "alias/demo"
122 value: "World"
123
124 - name: Always update a parameter store value and create a new version
125 community.aws.ssm_parameter:
126 name: "overwrite_example"
127 description: "This example will always overwrite the value"
128 string_type: "String"
129 value: "Test1234"
130 overwrite_value: "always"
131
132 - name: Create or update key/value pair in AWS SSM parameter store with tier
133 community.aws.ssm_parameter:
134 name: "Hello"
135 description: "This is your first key"
136 value: "World"
137 tier: "Advanced"
138
139 - name: recommend to use with aws_ssm lookup plugin
140 ansible.builtin.debug:
141 msg: "{{ lookup('amazon.aws.aws_ssm', 'Hello') }}"
142
143 - name: Create or update key/value pair in AWS SSM parameter store w/ tags
144 community.aws.ssm_parameter:
145 name: "Hello"
146 description: "This is your first key"
147 value: "World"
148 tags:
149 Environment: "dev"
150 Version: "1.0"
151 Confidentiality: "low"
152 Tag With Space: "foo bar"
153
154 - name: Add or update a tag on an existing parameter w/o removing existing tags
155 community.aws.ssm_parameter:
156 name: "Hello"
157 purge_tags: false
158 tags:
159 Contact: "person1"
160
161 - name: Delete all tags on an existing parameter
162 community.aws.ssm_parameter:
163 name: "Hello"
164 tags: {}
165 """
166
167 RETURN = r"""
168 parameter_metadata:
169 type: dict
170 description:
171 - Information about a parameter.
172 - Does not include the value of the parameter as this can be sensitive
173 information.
174 returned: success
175 contains:
176 data_type:
177 type: str
178 description: Parameter Data type.
179 example: text
180 returned: success
181 description:
182 type: str
183 description: Parameter key description.
184 example: This is your first key
185 returned: success
186 last_modified_date:
187 type: str
188 description: Time and date that the parameter was last modified.
189 example: '2022-06-20T09:56:58.573000+00:00'
190 returned: success
191 last_modified_user:
192 type: str
193 description: ARN of the last user to modify the parameter.
194 example: 'arn:aws:sts::123456789012:assumed-role/example-role/session=example'
195 returned: success
196 name:
197 type: str
198 description: Parameter key name.
199 example: Hello
200 returned: success
201 policies:
202 type: list
203 description: A list of policies associated with a parameter.
204 elements: dict
205 returned: success
206 contains:
207 policy_text:
208 type: str
209 description: The JSON text of the policy.
210 returned: success
211 policy_type:
212 type: str
213 description: The type of policy.
214 example: Expiration
215 returned: success
216 policy_status:
217 type: str
218 description: The status of the policy.
219 example: Pending
220 returned: success
221 tier:
222 type: str
223 description: Parameter tier.
224 example: Standard
225 returned: success
226 type:
227 type: str
228 description: Parameter type
229 example: String
230 returned: success
231 version:
232 type: int
233 description: Parameter version number
234 example: 3
235 returned: success
236 tags:
237 description: A dictionary representing the tags associated with the parameter.
238 type: dict
239 returned: when the parameter has tags
240 example: {'MyTagName': 'Some Value'}
241 version_added: 5.3.0
242 """
243
244 import time
245
246 try:
247 import botocore
248 from botocore.exceptions import BotoCoreError
249 from botocore.exceptions import ClientError
250 except ImportError:
251 pass # Handled by AnsibleAWSModule
252
253 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
254
255 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
256 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
257 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
258 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
259 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
260
261 from ansible_collections.community.aws.plugins.module_utils.base import BaseWaiterFactory
262 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
263
264
265 class ParameterWaiterFactory(BaseWaiterFactory):
266 def __init__(self, module):
267 client = module.client("ssm")
268 super(ParameterWaiterFactory, self).__init__(module, client)
269
270 @property
271 def _waiter_model_data(self):
272 data = super(ParameterWaiterFactory, self)._waiter_model_data
273 ssm_data = dict(
274 parameter_exists=dict(
275 operation="DescribeParameters",
276 delay=1,
277 maxAttempts=20,
278 acceptors=[
279 dict(state="retry", matcher="error", expected="ParameterNotFound"),
280 dict(state="retry", matcher="path", expected=True, argument="length(Parameters[].Name) == `0`"),
281 dict(state="success", matcher="path", expected=True, argument="length(Parameters[].Name) > `0`"),
282 ],
283 ),
284 parameter_deleted=dict(
285 operation="DescribeParameters",
286 delay=1,
287 maxAttempts=20,
288 acceptors=[
289 dict(state="retry", matcher="path", expected=True, argument="length(Parameters[].Name) > `0`"),
290 dict(state="success", matcher="path", expected=True, argument="length(Parameters[]) == `0`"),
291 dict(state="success", matcher="error", expected="ParameterNotFound"),
292 ],
293 ),
294 )
295 data.update(ssm_data)
296 return data
297
298
299 def _wait_exists(client, module, name):
300 if module.check_mode:
301 return
302 wf = ParameterWaiterFactory(module)
303 waiter = wf.get_waiter("parameter_exists")
304 try:
305 waiter.wait(
306 ParameterFilters=[{"Key": "Name", "Values": [name]}],
307 )
308 except botocore.exceptions.WaiterError:
309 module.warn("Timeout waiting for parameter to exist")
310 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
311 module.fail_json_aws(e, msg="Failed to describe parameter while waiting for creation")
312
313
314 def _wait_updated(client, module, name, version):
315 # Unfortunately we can't filter on the Version, as such we need something custom.
316 if module.check_mode:
317 return
318 for x in range(1, 10):
319 try:
320 parameter = describe_parameter(client, module, ParameterFilters=[{"Key": "Name", "Values": [name]}])
321 if parameter.get("Version", 0) > version:
322 return
323 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
324 module.fail_json_aws(e, msg="Failed to describe parameter while waiting for update")
325 time.sleep(1)
326
327
328 def _wait_deleted(client, module, name):
329 if module.check_mode:
330 return
331 wf = ParameterWaiterFactory(module)
332 waiter = wf.get_waiter("parameter_deleted")
333 try:
334 waiter.wait(
335 ParameterFilters=[{"Key": "Name", "Values": [name]}],
336 )
337 except botocore.exceptions.WaiterError:
338 module.warn("Timeout waiting for parameter to exist")
339 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
340 module.fail_json_aws(e, msg="Failed to describe parameter while waiting for deletion")
341
342
343 def tag_parameter(client, module, parameter_name, tags):
344 try:
345 return client.add_tags_to_resource(
346 aws_retry=True, ResourceType="Parameter", ResourceId=parameter_name, Tags=tags
347 )
348 except (BotoCoreError, ClientError) as e:
349 module.fail_json_aws(e, msg="Failed to add tag(s) to parameter")
350
351
352 def untag_parameter(client, module, parameter_name, tag_keys):
353 try:
354 return client.remove_tags_from_resource(
355 aws_retry=True, ResourceType="Parameter", ResourceId=parameter_name, TagKeys=tag_keys
356 )
357 except (BotoCoreError, ClientError) as e:
358 module.fail_json_aws(e, msg="Failed to remove tag(s) from parameter")
359
360
361 def get_parameter_tags(client, module, parameter_name):
362 try:
363 tags = client.list_tags_for_resource(aws_retry=True, ResourceType="Parameter", ResourceId=parameter_name)[
364 "TagList"
365 ]
366 tags_dict = boto3_tag_list_to_ansible_dict(tags)
367 return tags_dict
368 except (BotoCoreError, ClientError) as e:
369 module.fail_json_aws(e, msg="Unable to retrieve parameter tags")
370
371
372 def update_parameter_tags(client, module, parameter_name, supplied_tags):
373 changed = False
374 response = {}
375
376 if supplied_tags is None:
377 return False, response
378
379 current_tags = get_parameter_tags(client, module, parameter_name)
380 tags_to_add, tags_to_remove = compare_aws_tags(current_tags, supplied_tags, module.params.get("purge_tags"))
381
382 if tags_to_add:
383 if module.check_mode:
384 return True, response
385 response = tag_parameter(client, module, parameter_name, ansible_dict_to_boto3_tag_list(tags_to_add))
386 changed = True
387 if tags_to_remove:
388 if module.check_mode:
389 return True, response
390 response = untag_parameter(client, module, parameter_name, tags_to_remove)
391 changed = True
392
393 return changed, response
394
395
396 def update_parameter(client, module, **args):
397 changed = False
398 response = {}
399 if module.check_mode:
400 return True, response
401
402 try:
403 response = client.put_parameter(aws_retry=True, **args)
404 changed = True
405 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as exc:
406 module.fail_json_aws(exc, msg="setting parameter")
407
408 return changed, response
409
410
411 @AWSRetry.jittered_backoff()
412 def describe_parameter(client, module, **args):
413 paginator = client.get_paginator("describe_parameters")
414 existing_parameter = paginator.paginate(**args).build_full_result()
415
416 if not existing_parameter["Parameters"]:
417 return None
418
419 tags_dict = get_parameter_tags(client, module, module.params.get("name"))
420 existing_parameter["Parameters"][0]["tags"] = tags_dict
421
422 return existing_parameter["Parameters"][0]
423
424
425 def create_update_parameter(client, module):
426 changed = False
427 existing_parameter = None
428 response = {}
429
430 args = dict(Name=module.params.get("name"), Type=module.params.get("string_type"), Tier=module.params.get("tier"))
431
432 if module.params.get("overwrite_value") in ("always", "changed"):
433 args.update(Overwrite=True)
434 else:
435 args.update(Overwrite=False)
436
437 if module.params.get("value") is not None:
438 args.update(Value=module.params.get("value"))
439
440 if module.params.get("description"):
441 args.update(Description=module.params.get("description"))
442
443 if module.params.get("string_type") == "SecureString":
444 args.update(KeyId=module.params.get("key_id"))
445
446 try:
447 existing_parameter = client.get_parameter(aws_retry=True, Name=args["Name"], WithDecryption=True)
448 except botocore.exceptions.ClientError:
449 pass
450 except botocore.exceptions.BotoCoreError as e:
451 module.fail_json_aws(e, msg="fetching parameter")
452
453 if existing_parameter:
454 original_version = existing_parameter["Parameter"]["Version"]
455 if "Value" not in args:
456 args["Value"] = existing_parameter["Parameter"]["Value"]
457
458 if module.params.get("overwrite_value") == "always":
459 (changed, response) = update_parameter(client, module, **args)
460
461 elif module.params.get("overwrite_value") == "changed":
462 if existing_parameter["Parameter"]["Type"] != args["Type"]:
463 (changed, response) = update_parameter(client, module, **args)
464
465 elif existing_parameter["Parameter"]["Value"] != args["Value"]:
466 (changed, response) = update_parameter(client, module, **args)
467
468 elif args.get("Description"):
469 # Description field not available from get_parameter function so get it from describe_parameters
470 try:
471 describe_existing_parameter = describe_parameter(
472 client, module, ParameterFilters=[{"Key": "Name", "Values": [args["Name"]]}]
473 )
474 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
475 module.fail_json_aws(e, msg="getting description value")
476
477 if describe_existing_parameter.get("Description") != args["Description"]:
478 (changed, response) = update_parameter(client, module, **args)
479 if changed:
480 _wait_updated(client, module, module.params.get("name"), original_version)
481
482 # Handle tag updates for existing parameters
483 if module.params.get("overwrite_value") != "never":
484 tags_changed, tags_response = update_parameter_tags(
485 client, module, existing_parameter["Parameter"]["Name"], module.params.get("tags")
486 )
487
488 changed = changed or tags_changed
489
490 if tags_response:
491 response["tag_updates"] = tags_response
492
493 else:
494 # Add tags in initial creation request
495 if module.params.get("tags"):
496 args.update(Tags=ansible_dict_to_boto3_tag_list(module.params.get("tags")))
497 # Overwrite=True conflicts with tags and is not needed for new param
498 args.update(Overwrite=False)
499
500 (changed, response) = update_parameter(client, module, **args)
501 _wait_exists(client, module, module.params.get("name"))
502
503 return changed, response
504
505
506 def delete_parameter(client, module):
507 response = {}
508
509 try:
510 existing_parameter = client.get_parameter(aws_retry=True, Name=module.params.get("name"), WithDecryption=True)
511 except is_boto3_error_code("ParameterNotFound"):
512 return False, {}
513 except botocore.exceptions.ClientError:
514 # If we can't describe the parameter we may still be able to delete it
515 existing_parameter = True
516 except botocore.exceptions.BotoCoreError as e:
517 module.fail_json_aws(e, msg="setting parameter")
518
519 if not existing_parameter:
520 return False, {}
521 if module.check_mode:
522 return True, {}
523
524 try:
525 response = client.delete_parameter(aws_retry=True, Name=module.params.get("name"))
526 except is_boto3_error_code("ParameterNotFound"):
527 return False, {}
528 except (
529 botocore.exceptions.ClientError,
530 botocore.exceptions.BotoCoreError,
531 ) as e: # pylint: disable=duplicate-except
532 module.fail_json_aws(e, msg="deleting parameter")
533
534 _wait_deleted(client, module, module.params.get("name"))
535
536 return True, response
537
538
539 def setup_client(module):
540 retry_decorator = AWSRetry.jittered_backoff()
541 connection = module.client("ssm", retry_decorator=retry_decorator)
542 return connection
543
544
545 def setup_module_object():
546 argument_spec = dict(
547 name=dict(required=True),
548 description=dict(),
549 value=dict(required=False, no_log=True),
550 state=dict(default="present", choices=["present", "absent"]),
551 string_type=dict(default="String", choices=["String", "StringList", "SecureString"], aliases=["type"]),
552 decryption=dict(default=True, type="bool"),
553 key_id=dict(default="alias/aws/ssm"),
554 overwrite_value=dict(default="changed", choices=["never", "changed", "always"]),
555 tier=dict(default="Standard", choices=["Standard", "Advanced", "Intelligent-Tiering"]),
556 tags=dict(type="dict", aliases=["resource_tags"]),
557 purge_tags=dict(type="bool", default=True),
558 )
559
560 return AnsibleAWSModule(
561 argument_spec=argument_spec,
562 supports_check_mode=True,
563 )
564
565
566 def main():
567 module = setup_module_object()
568 state = module.params.get("state")
569 client = setup_client(module)
570
571 invocations = {
572 "present": create_update_parameter,
573 "absent": delete_parameter,
574 }
575 (changed, response) = invocations[state](client, module)
576
577 result = {"response": response}
578
579 try:
580 parameter_metadata = describe_parameter(
581 client, module, ParameterFilters=[{"Key": "Name", "Values": [module.params.get("name")]}]
582 )
583 except is_boto3_error_code("ParameterNotFound"):
584 return False, {}
585 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
586 module.fail_json_aws(e, msg="to describe parameter")
587 if parameter_metadata:
588 result["parameter_metadata"] = camel_dict_to_snake_dict(parameter_metadata, ignore_list=["tags"])
589
590 module.exit_json(changed=changed, **result)
591
592
593 if __name__ == "__main__":
594 main()