Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: 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: kinesis_stream
10 version_added: 1.0.0
11 short_description: Manage a Kinesis Stream.
12 description:
13 - Create or Delete a Kinesis Stream.
14 - Update the retention period of a Kinesis Stream.
15 - Update Tags on a Kinesis Stream.
16 - Enable/disable server side encryption on a Kinesis Stream.
17 author:
18 - Allen Sanabria (@linuxdynasty)
19 options:
20 name:
21 description:
22 - The name of the Kinesis Stream you are managing.
23 required: true
24 type: str
25 shards:
26 description:
27 - The number of shards you want to have with this stream.
28 - This is required when I(state=present)
29 type: int
30 retention_period:
31 description:
32 - The length of time (in hours) data records are accessible after they are added to
33 the stream.
34 - The default retention period is 24 hours and can not be less than 24 hours.
35 - The maximum retention period is 168 hours.
36 - The retention period can be modified during any point in time.
37 type: int
38 state:
39 description:
40 - Create or Delete the Kinesis Stream.
41 default: present
42 choices: [ 'present', 'absent' ]
43 type: str
44 wait:
45 description:
46 - Wait for operation to complete before returning.
47 default: true
48 type: bool
49 wait_timeout:
50 description:
51 - How many seconds to wait for an operation to complete before timing out.
52 default: 300
53 type: int
54 tags:
55 description:
56 - "A dictionary of resource tags of the form: C({ tag1: value1, tag2: value2 })."
57 aliases: [ "resource_tags" ]
58 type: dict
59 encryption_state:
60 description:
61 - Enable or Disable encryption on the Kinesis Stream.
62 choices: [ 'enabled', 'disabled' ]
63 type: str
64 encryption_type:
65 description:
66 - The type of encryption.
67 - Defaults to C(KMS)
68 choices: ['KMS', 'NONE']
69 type: str
70 key_id:
71 description:
72 - The GUID or alias for the KMS key.
73 type: str
74 extends_documentation_fragment:
75 - amazon.aws.common.modules
76 - amazon.aws.region.modules
77 - amazon.aws.boto3
78 """
79
80 EXAMPLES = r"""
81 # Note: These examples do not set authentication details, see the AWS Guide for details.
82
83 # Basic creation example:
84 - name: Set up Kinesis Stream with 10 shards and wait for the stream to become ACTIVE
85 community.aws.kinesis_stream:
86 name: test-stream
87 shards: 10
88 wait: true
89 wait_timeout: 600
90 register: test_stream
91
92 # Basic creation example with tags:
93 - name: Set up Kinesis Stream with 10 shards, tag the environment, and wait for the stream to become ACTIVE
94 community.aws.kinesis_stream:
95 name: test-stream
96 shards: 10
97 tags:
98 Env: development
99 wait: true
100 wait_timeout: 600
101 register: test_stream
102
103 # Basic creation example with tags and increase the retention period from the default 24 hours to 48 hours:
104 - name: Set up Kinesis Stream with 10 shards, tag the environment, increase the retention period and wait for the stream to become ACTIVE
105 community.aws.kinesis_stream:
106 name: test-stream
107 retention_period: 48
108 shards: 10
109 tags:
110 Env: development
111 wait: true
112 wait_timeout: 600
113 register: test_stream
114
115 # Basic delete example:
116 - name: Delete Kinesis Stream test-stream and wait for it to finish deleting.
117 community.aws.kinesis_stream:
118 name: test-stream
119 state: absent
120 wait: true
121 wait_timeout: 600
122 register: test_stream
123
124 # Basic enable encryption example:
125 - name: Encrypt Kinesis Stream test-stream.
126 community.aws.kinesis_stream:
127 name: test-stream
128 state: present
129 shards: 1
130 encryption_state: enabled
131 encryption_type: KMS
132 key_id: alias/aws/kinesis
133 wait: true
134 wait_timeout: 600
135 register: test_stream
136
137 # Basic disable encryption example:
138 - name: Encrypt Kinesis Stream test-stream.
139 community.aws.kinesis_stream:
140 name: test-stream
141 state: present
142 shards: 1
143 encryption_state: disabled
144 encryption_type: KMS
145 key_id: alias/aws/kinesis
146 wait: true
147 wait_timeout: 600
148 register: test_stream
149 """
150
151 RETURN = r"""
152 stream_name:
153 description: The name of the Kinesis Stream.
154 returned: when state == present.
155 type: str
156 sample: "test-stream"
157 stream_arn:
158 description: The amazon resource identifier
159 returned: when state == present.
160 type: str
161 sample: "arn:aws:kinesis:east-side:123456789:stream/test-stream"
162 stream_status:
163 description: The current state of the Kinesis Stream.
164 returned: when state == present.
165 type: str
166 sample: "ACTIVE"
167 retention_period_hours:
168 description: Number of hours messages will be kept for a Kinesis Stream.
169 returned: when state == present.
170 type: int
171 sample: 24
172 tags:
173 description: Dictionary containing all the tags associated with the Kinesis stream.
174 returned: when state == present.
175 type: dict
176 sample: {
177 "Name": "Splunk",
178 "Env": "development"
179 }
180 """
181
182 import time
183
184 try:
185 import botocore
186 except ImportError:
187 pass # Handled by AnsibleAWSModule
188
189 from ansible.module_utils._text import to_native
190 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
191
192 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
193 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
194
195 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
196
197
198 def get_tags(client, stream_name):
199 """Retrieve the tags for a Kinesis Stream.
200 Args:
201 client (botocore.client.EC2): Boto3 client.
202 stream_name (str): Name of the Kinesis stream.
203
204 Basic Usage:
205 >>> client = boto3.client('kinesis')
206 >>> stream_name = 'test-stream'
207 >> get_tags(client, stream_name)
208
209 Returns:
210 Tuple (bool, str, dict)
211 """
212 err_msg = ""
213 success = False
214 params = {
215 "StreamName": stream_name,
216 }
217 results = dict()
218 try:
219 results = client.list_tags_for_stream(**params)["Tags"]
220 success = True
221 except botocore.exceptions.ClientError as e:
222 err_msg = to_native(e)
223
224 return success, err_msg, boto3_tag_list_to_ansible_dict(results)
225
226
227 def find_stream(client, stream_name):
228 """Retrieve a Kinesis Stream.
229 Args:
230 client (botocore.client.EC2): Boto3 client.
231 stream_name (str): Name of the Kinesis stream.
232
233 Basic Usage:
234 >>> client = boto3.client('kinesis')
235 >>> stream_name = 'test-stream'
236
237 Returns:
238 Tuple (bool, str, dict)
239 """
240 err_msg = ""
241 success = False
242 params = {
243 "StreamName": stream_name,
244 }
245 results = dict()
246 has_more_shards = True
247 shards = list()
248 try:
249 while has_more_shards:
250 results = client.describe_stream(**params)["StreamDescription"]
251 shards.extend(results.pop("Shards"))
252 has_more_shards = results["HasMoreShards"]
253 if has_more_shards:
254 params["ExclusiveStartShardId"] = shards[-1]["ShardId"]
255 results["Shards"] = shards
256 num_closed_shards = len([s for s in shards if "EndingSequenceNumber" in s["SequenceNumberRange"]])
257 results["OpenShardsCount"] = len(shards) - num_closed_shards
258 results["ClosedShardsCount"] = num_closed_shards
259 results["ShardsCount"] = len(shards)
260 success = True
261 except botocore.exceptions.ClientError as e:
262 err_msg = to_native(e)
263
264 return success, err_msg, results
265
266
267 def wait_for_status(client, stream_name, status, wait_timeout=300, check_mode=False):
268 """Wait for the status to change for a Kinesis Stream.
269 Args:
270 client (botocore.client.EC2): Boto3 client
271 stream_name (str): The name of the kinesis stream.
272 status (str): The status to wait for.
273 examples. status=available, status=deleted
274
275 Kwargs:
276 wait_timeout (int): Number of seconds to wait, until this timeout is reached.
277 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
278 default=False
279
280 Basic Usage:
281 >>> client = boto3.client('kinesis')
282 >>> stream_name = 'test-stream'
283 >>> wait_for_status(client, stream_name, 'ACTIVE', 300)
284
285 Returns:
286 Tuple (bool, str, dict)
287 """
288 polling_increment_secs = 5
289 wait_timeout = time.time() + wait_timeout
290 status_achieved = False
291 stream = dict()
292 err_msg = ""
293
294 while wait_timeout > time.time():
295 try:
296 find_success, find_msg, stream = find_stream(client, stream_name)
297 if check_mode:
298 status_achieved = True
299 break
300
301 if status != "DELETING":
302 if find_success and stream:
303 if stream.get("StreamStatus") == status:
304 status_achieved = True
305 break
306
307 else:
308 if not find_success:
309 status_achieved = True
310 break
311
312 except botocore.exceptions.ClientError as e:
313 err_msg = to_native(e)
314
315 time.sleep(polling_increment_secs)
316
317 if not status_achieved:
318 err_msg = "Wait time out reached, while waiting for results"
319 else:
320 err_msg = f"Status {status} achieved successfully"
321
322 return status_achieved, err_msg, stream
323
324
325 def tags_action(client, stream_name, tags, action="create", check_mode=False):
326 """Create or delete multiple tags from a Kinesis Stream.
327 Args:
328 client (botocore.client.EC2): Boto3 client.
329 resource_id (str): The Amazon resource id.
330 tags (list): List of dictionaries.
331 examples.. [{Name: "", Values: [""]}]
332
333 Kwargs:
334 action (str): The action to perform.
335 valid actions == create and delete
336 default=create
337 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
338 default=False
339
340 Basic Usage:
341 >>> client = boto3.client('ec2')
342 >>> resource_id = 'pcx-123345678'
343 >>> tags = {'env': 'development'}
344 >>> update_tags(client, resource_id, tags)
345 [True, '']
346
347 Returns:
348 List (bool, str)
349 """
350 success = False
351 err_msg = ""
352 params = {"StreamName": stream_name}
353 try:
354 if not check_mode:
355 if action == "create":
356 params["Tags"] = tags
357 client.add_tags_to_stream(**params)
358 success = True
359 elif action == "delete":
360 params["TagKeys"] = tags
361 client.remove_tags_from_stream(**params)
362 success = True
363 else:
364 err_msg = f"Invalid action {action}"
365 else:
366 if action == "create":
367 success = True
368 elif action == "delete":
369 success = True
370 else:
371 err_msg = f"Invalid action {action}"
372
373 except botocore.exceptions.ClientError as e:
374 err_msg = to_native(e)
375
376 return success, err_msg
377
378
379 def update_tags(client, stream_name, tags, check_mode=False):
380 """Update tags for an amazon resource.
381 Args:
382 resource_id (str): The Amazon resource id.
383 tags (dict): Dictionary of tags you want applied to the Kinesis stream.
384
385 Kwargs:
386 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
387 default=False
388
389 Basic Usage:
390 >>> client = boto3.client('ec2')
391 >>> stream_name = 'test-stream'
392 >>> tags = {'env': 'development'}
393 >>> update_tags(client, stream_name, tags)
394 [True, '']
395
396 Return:
397 Tuple (bool, str)
398 """
399 success = False
400 changed = False
401 err_msg = ""
402 tag_success, tag_msg, current_tags = get_tags(client, stream_name)
403
404 tags_to_set, tags_to_delete = compare_aws_tags(
405 current_tags,
406 tags,
407 purge_tags=True,
408 )
409 if tags_to_delete:
410 delete_success, delete_msg = tags_action(
411 client, stream_name, tags_to_delete, action="delete", check_mode=check_mode
412 )
413 if not delete_success:
414 return delete_success, changed, delete_msg
415
416 if tags_to_set:
417 create_success, create_msg = tags_action(
418 client, stream_name, tags_to_set, action="create", check_mode=check_mode
419 )
420 if create_success:
421 changed = True
422 return create_success, changed, create_msg
423
424 return success, changed, err_msg
425
426
427 def stream_action(client, stream_name, shard_count=1, action="create", timeout=300, check_mode=False):
428 """Create or Delete an Amazon Kinesis Stream.
429 Args:
430 client (botocore.client.EC2): Boto3 client.
431 stream_name (str): The name of the kinesis stream.
432
433 Kwargs:
434 shard_count (int): Number of shards this stream will use.
435 action (str): The action to perform.
436 valid actions == create and delete
437 default=create
438 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
439 default=False
440
441 Basic Usage:
442 >>> client = boto3.client('kinesis')
443 >>> stream_name = 'test-stream'
444 >>> shard_count = 20
445 >>> stream_action(client, stream_name, shard_count, action='create')
446
447 Returns:
448 List (bool, str)
449 """
450 success = False
451 err_msg = ""
452 params = {"StreamName": stream_name}
453 try:
454 if not check_mode:
455 if action == "create":
456 params["ShardCount"] = shard_count
457 client.create_stream(**params)
458 success = True
459 elif action == "delete":
460 client.delete_stream(**params)
461 success = True
462 else:
463 err_msg = f"Invalid action {action}"
464 else:
465 if action == "create":
466 success = True
467 elif action == "delete":
468 success = True
469 else:
470 err_msg = f"Invalid action {action}"
471
472 except botocore.exceptions.ClientError as e:
473 err_msg = to_native(e)
474
475 return success, err_msg
476
477
478 def stream_encryption_action(
479 client, stream_name, action="start_encryption", encryption_type="", key_id="", timeout=300, check_mode=False
480 ):
481 """Create, Encrypt or Delete an Amazon Kinesis Stream.
482 Args:
483 client (botocore.client.EC2): Boto3 client.
484 stream_name (str): The name of the kinesis stream.
485
486 Kwargs:
487 shard_count (int): Number of shards this stream will use.
488 action (str): The action to perform.
489 valid actions == create and delete
490 default=create
491 encryption_type (str): NONE or KMS
492 key_id (str): The GUID or alias for the KMS key
493 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
494 default=False
495
496 Basic Usage:
497 >>> client = boto3.client('kinesis')
498 >>> stream_name = 'test-stream'
499 >>> shard_count = 20
500 >>> stream_action(client, stream_name, shard_count, action='create', encryption_type='KMS',key_id='alias/aws')
501
502 Returns:
503 List (bool, str)
504 """
505 success = False
506 err_msg = ""
507 params = {"StreamName": stream_name}
508 try:
509 if not check_mode:
510 if action == "start_encryption":
511 params["EncryptionType"] = encryption_type
512 params["KeyId"] = key_id
513 client.start_stream_encryption(**params)
514 success = True
515 elif action == "stop_encryption":
516 params["EncryptionType"] = encryption_type
517 params["KeyId"] = key_id
518 client.stop_stream_encryption(**params)
519 success = True
520 else:
521 err_msg = f"Invalid encryption action {action}"
522 else:
523 if action == "start_encryption":
524 success = True
525 elif action == "stop_encryption":
526 success = True
527 else:
528 err_msg = f"Invalid encryption action {action}"
529
530 except botocore.exceptions.ClientError as e:
531 err_msg = to_native(e)
532
533 return success, err_msg
534
535
536 def retention_action(client, stream_name, retention_period=24, action="increase", check_mode=False):
537 """Increase or Decrease the retention of messages in the Kinesis stream.
538 Args:
539 client (botocore.client.EC2): Boto3 client.
540 stream_name (str): The name of the kinesis stream.
541
542 Kwargs:
543 retention_period (int): This is how long messages will be kept before
544 they are discarded. This can not be less than 24 hours.
545 action (str): The action to perform.
546 valid actions == create and delete
547 default=create
548 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
549 default=False
550
551 Basic Usage:
552 >>> client = boto3.client('kinesis')
553 >>> stream_name = 'test-stream'
554 >>> retention_period = 48
555 >>> retention_action(client, stream_name, retention_period, action='increase')
556
557 Returns:
558 Tuple (bool, str)
559 """
560 success = False
561 err_msg = ""
562 params = {"StreamName": stream_name}
563 try:
564 if not check_mode:
565 if action == "increase":
566 params["RetentionPeriodHours"] = retention_period
567 client.increase_stream_retention_period(**params)
568 success = True
569 err_msg = f"Retention Period increased successfully to {retention_period}"
570 elif action == "decrease":
571 params["RetentionPeriodHours"] = retention_period
572 client.decrease_stream_retention_period(**params)
573 success = True
574 err_msg = f"Retention Period decreased successfully to {retention_period}"
575 else:
576 err_msg = f"Invalid action {action}"
577 else:
578 if action == "increase":
579 success = True
580 elif action == "decrease":
581 success = True
582 else:
583 err_msg = f"Invalid action {action}"
584
585 except botocore.exceptions.ClientError as e:
586 err_msg = to_native(e)
587
588 return success, err_msg
589
590
591 def update_shard_count(client, stream_name, number_of_shards=1, check_mode=False):
592 """Increase or Decrease the number of shards in the Kinesis stream.
593 Args:
594 client (botocore.client.EC2): Boto3 client.
595 stream_name (str): The name of the kinesis stream.
596
597 Kwargs:
598 number_of_shards (int): Number of shards this stream will use.
599 default=1
600 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
601 default=False
602
603 Basic Usage:
604 >>> client = boto3.client('kinesis')
605 >>> stream_name = 'test-stream'
606 >>> number_of_shards = 3
607 >>> update_shard_count(client, stream_name, number_of_shards)
608
609 Returns:
610 Tuple (bool, str)
611 """
612 success = True
613 err_msg = ""
614 params = {"StreamName": stream_name, "ScalingType": "UNIFORM_SCALING"}
615 if not check_mode:
616 params["TargetShardCount"] = number_of_shards
617 try:
618 client.update_shard_count(**params)
619 except botocore.exceptions.ClientError as e:
620 return False, str(e)
621
622 return success, err_msg
623
624
625 def update(
626 client,
627 current_stream,
628 stream_name,
629 number_of_shards=1,
630 retention_period=None,
631 tags=None,
632 wait=False,
633 wait_timeout=300,
634 check_mode=False,
635 ):
636 """Update an Amazon Kinesis Stream.
637 Args:
638 client (botocore.client.EC2): Boto3 client.
639 stream_name (str): The name of the kinesis stream.
640
641 Kwargs:
642 number_of_shards (int): Number of shards this stream will use.
643 default=1
644 retention_period (int): This is how long messages will be kept before
645 they are discarded. This can not be less than 24 hours.
646 tags (dict): The tags you want applied.
647 wait (bool): Wait until Stream is ACTIVE.
648 default=False
649 wait_timeout (int): How long to wait until this operation is considered failed.
650 default=300
651 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
652 default=False
653
654 Basic Usage:
655 >>> client = boto3.client('kinesis')
656 >>> current_stream = {
657 'ShardCount': 3,
658 'HasMoreShards': True,
659 'RetentionPeriodHours': 24,
660 'StreamName': 'test-stream',
661 'StreamARN': 'arn:aws:kinesis:us-west-2:123456789:stream/test-stream',
662 'StreamStatus': "ACTIVE'
663 }
664 >>> stream_name = 'test-stream'
665 >>> retention_period = 48
666 >>> number_of_shards = 10
667 >>> update(client, current_stream, stream_name,
668 number_of_shards, retention_period )
669
670 Returns:
671 Tuple (bool, bool, str)
672 """
673 success = True
674 changed = False
675 err_msg = ""
676 if retention_period:
677 if wait:
678 wait_success, wait_msg, current_stream = wait_for_status(
679 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
680 )
681 if not wait_success:
682 return wait_success, False, wait_msg
683
684 if current_stream.get("StreamStatus") == "ACTIVE":
685 retention_changed = False
686 if retention_period > current_stream["RetentionPeriodHours"]:
687 retention_changed, retention_msg = retention_action(
688 client, stream_name, retention_period, action="increase", check_mode=check_mode
689 )
690
691 elif retention_period < current_stream["RetentionPeriodHours"]:
692 retention_changed, retention_msg = retention_action(
693 client, stream_name, retention_period, action="decrease", check_mode=check_mode
694 )
695
696 elif retention_period == current_stream["RetentionPeriodHours"]:
697 retention_msg = f"Retention {retention_period} is the same as {current_stream['RetentionPeriodHours']}"
698 success = True
699
700 if retention_changed:
701 success = True
702 changed = True
703
704 err_msg = retention_msg
705 if changed and wait:
706 wait_success, wait_msg, current_stream = wait_for_status(
707 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
708 )
709 if not wait_success:
710 return wait_success, False, wait_msg
711 elif changed and not wait:
712 stream_found, stream_msg, current_stream = find_stream(client, stream_name)
713 if stream_found:
714 if current_stream["StreamStatus"] != "ACTIVE":
715 err_msg = f"Retention Period for {stream_name} is in the process of updating"
716 return success, changed, err_msg
717 else:
718 err_msg = (
719 "StreamStatus has to be ACTIVE in order to modify the retention period."
720 f" Current status is {current_stream.get('StreamStatus', 'UNKNOWN')}"
721 )
722 return success, changed, err_msg
723
724 if current_stream["OpenShardsCount"] != number_of_shards:
725 success, err_msg = update_shard_count(client, stream_name, number_of_shards, check_mode=check_mode)
726
727 if not success:
728 return success, changed, err_msg
729
730 changed = True
731
732 if wait:
733 wait_success, wait_msg, current_stream = wait_for_status(
734 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
735 )
736 if not wait_success:
737 return wait_success, changed, wait_msg
738 else:
739 stream_found, stream_msg, current_stream = find_stream(client, stream_name)
740 if stream_found and current_stream["StreamStatus"] != "ACTIVE":
741 err_msg = f"Number of shards for {stream_name} is in the process of updating"
742 return success, changed, err_msg
743
744 if tags:
745 tag_success, tag_changed, err_msg = update_tags(client, stream_name, tags, check_mode=check_mode)
746 changed |= tag_changed
747 if wait:
748 success, err_msg, status_stream = wait_for_status(
749 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
750 )
751 if success and changed:
752 err_msg = f"Kinesis Stream {stream_name} updated successfully."
753 elif success and not changed:
754 err_msg = f"Kinesis Stream {stream_name} did not change."
755
756 return success, changed, err_msg
757
758
759 def create_stream(
760 client,
761 stream_name,
762 number_of_shards=1,
763 retention_period=None,
764 tags=None,
765 wait=False,
766 wait_timeout=300,
767 check_mode=False,
768 ):
769 """Create an Amazon Kinesis Stream.
770 Args:
771 client (botocore.client.EC2): Boto3 client.
772 stream_name (str): The name of the kinesis stream.
773
774 Kwargs:
775 number_of_shards (int): Number of shards this stream will use.
776 default=1
777 retention_period (int): Can not be less than 24 hours
778 default=None
779 tags (dict): The tags you want applied.
780 default=None
781 wait (bool): Wait until Stream is ACTIVE.
782 default=False
783 wait_timeout (int): How long to wait until this operation is considered failed.
784 default=300
785 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
786 default=False
787
788 Basic Usage:
789 >>> client = boto3.client('kinesis')
790 >>> stream_name = 'test-stream'
791 >>> number_of_shards = 10
792 >>> tags = {'env': 'test'}
793 >>> create_stream(client, stream_name, number_of_shards, tags=tags)
794
795 Returns:
796 Tuple (bool, bool, str, dict)
797 """
798 success = False
799 changed = False
800 err_msg = ""
801 results = dict()
802
803 stream_found, stream_msg, current_stream = find_stream(client, stream_name)
804
805 if stream_found and current_stream.get("StreamStatus") == "DELETING" and wait:
806 wait_success, wait_msg, current_stream = wait_for_status(
807 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
808 )
809
810 if stream_found and current_stream.get("StreamStatus") != "DELETING":
811 success, changed, err_msg = update(
812 client,
813 current_stream,
814 stream_name,
815 number_of_shards,
816 retention_period,
817 tags,
818 wait,
819 wait_timeout,
820 check_mode=check_mode,
821 )
822 else:
823 create_success, create_msg = stream_action(
824 client, stream_name, number_of_shards, action="create", check_mode=check_mode
825 )
826 if not create_success:
827 changed = True
828 err_msg = f"Failed to create Kinesis stream: {create_msg}"
829 return False, True, err_msg, {}
830 else:
831 changed = True
832 if wait:
833 wait_success, wait_msg, results = wait_for_status(
834 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
835 )
836 err_msg = f"Kinesis Stream {stream_name} is in the process of being created"
837 if not wait_success:
838 return wait_success, True, wait_msg, results
839 else:
840 err_msg = f"Kinesis Stream {stream_name} created successfully"
841
842 if tags:
843 changed, err_msg = tags_action(client, stream_name, tags, action="create", check_mode=check_mode)
844 if changed:
845 success = True
846 if not success:
847 return success, changed, err_msg, results
848
849 stream_found, stream_msg, current_stream = find_stream(client, stream_name)
850 if retention_period and current_stream.get("StreamStatus") == "ACTIVE":
851 changed, err_msg = retention_action(
852 client, stream_name, retention_period, action="increase", check_mode=check_mode
853 )
854 if changed:
855 success = True
856 if not success:
857 return success, changed, err_msg, results
858 else:
859 err_msg = (
860 "StreamStatus has to be ACTIVE in order to modify the retention period."
861 f" Current status is {current_stream.get('StreamStatus', 'UNKNOWN')}"
862 )
863 success = create_success
864 changed = True
865
866 if success:
867 stream_found, stream_msg, results = find_stream(client, stream_name)
868 tag_success, tag_msg, current_tags = get_tags(client, stream_name)
869 if check_mode:
870 current_tags = tags
871
872 if not current_tags:
873 current_tags = dict()
874
875 results = camel_dict_to_snake_dict(results)
876 results["tags"] = current_tags
877
878 return success, changed, err_msg, results
879
880
881 def delete_stream(client, stream_name, wait=False, wait_timeout=300, check_mode=False):
882 """Delete an Amazon Kinesis Stream.
883 Args:
884 client (botocore.client.EC2): Boto3 client.
885 stream_name (str): The name of the kinesis stream.
886
887 Kwargs:
888 wait (bool): Wait until Stream is ACTIVE.
889 default=False
890 wait_timeout (int): How long to wait until this operation is considered failed.
891 default=300
892 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
893 default=False
894
895 Basic Usage:
896 >>> client = boto3.client('kinesis')
897 >>> stream_name = 'test-stream'
898 >>> delete_stream(client, stream_name)
899
900 Returns:
901 Tuple (bool, bool, str, dict)
902 """
903 success = False
904 changed = False
905 err_msg = ""
906 results = dict()
907 stream_found, stream_msg, current_stream = find_stream(client, stream_name)
908 if stream_found:
909 success, err_msg = stream_action(client, stream_name, action="delete", check_mode=check_mode)
910 if success:
911 changed = True
912 if wait:
913 success, err_msg, results = wait_for_status(
914 client, stream_name, "DELETING", wait_timeout, check_mode=check_mode
915 )
916 err_msg = f"Stream {stream_name} deleted successfully"
917 if not success:
918 return success, True, err_msg, results
919 else:
920 err_msg = f"Stream {stream_name} is in the process of being deleted"
921 else:
922 success = True
923 changed = False
924 err_msg = f"Stream {stream_name} does not exist"
925
926 return success, changed, err_msg, results
927
928
929 def start_stream_encryption(
930 client, stream_name, encryption_type="", key_id="", wait=False, wait_timeout=300, check_mode=False
931 ):
932 """Start encryption on an Amazon Kinesis Stream.
933 Args:
934 client (botocore.client.EC2): Boto3 client.
935 stream_name (str): The name of the kinesis stream.
936
937 Kwargs:
938 encryption_type (str): KMS or NONE
939 key_id (str): KMS key GUID or alias
940 wait (bool): Wait until Stream is ACTIVE.
941 default=False
942 wait_timeout (int): How long to wait until this operation is considered failed.
943 default=300
944 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
945 default=False
946
947 Basic Usage:
948 >>> client = boto3.client('kinesis')
949 >>> stream_name = 'test-stream'
950 >>> key_id = 'alias/aws'
951 >>> encryption_type = 'KMS'
952 >>> start_stream_encryption(client, stream_name,encryption_type,key_id)
953
954 Returns:
955 Tuple (bool, bool, str, dict)
956 """
957 success = False
958 changed = False
959 err_msg = ""
960
961 results = dict()
962 stream_found, stream_msg, current_stream = find_stream(client, stream_name)
963 if stream_found:
964 if current_stream.get("EncryptionType") == encryption_type and current_stream.get("KeyId") == key_id:
965 changed = False
966 success = True
967 err_msg = f"Kinesis Stream {stream_name} encryption already configured."
968 else:
969 success, err_msg = stream_encryption_action(
970 client,
971 stream_name,
972 action="start_encryption",
973 encryption_type=encryption_type,
974 key_id=key_id,
975 check_mode=check_mode,
976 )
977 if success:
978 changed = True
979 if wait:
980 success, err_msg, results = wait_for_status(
981 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
982 )
983 err_msg = f"Kinesis Stream {stream_name} encryption started successfully."
984 if not success:
985 return success, True, err_msg, results
986 else:
987 err_msg = f"Kinesis Stream {stream_name} is in the process of starting encryption."
988 else:
989 success = True
990 changed = False
991 err_msg = f"Kinesis Stream {stream_name} does not exist"
992
993 if success:
994 stream_found, stream_msg, results = find_stream(client, stream_name)
995 tag_success, tag_msg, current_tags = get_tags(client, stream_name)
996 if not current_tags:
997 current_tags = dict()
998
999 results = camel_dict_to_snake_dict(results)
1000 results["tags"] = current_tags
1001
1002 return success, changed, err_msg, results
1003
1004
1005 def stop_stream_encryption(
1006 client, stream_name, encryption_type="", key_id="", wait=True, wait_timeout=300, check_mode=False
1007 ):
1008 """Stop encryption on an Amazon Kinesis Stream.
1009 Args:
1010 client (botocore.client.EC2): Boto3 client.
1011 stream_name (str): The name of the kinesis stream.
1012
1013 Kwargs:
1014 encryption_type (str): KMS or NONE
1015 key_id (str): KMS key GUID or alias
1016 wait (bool): Wait until Stream is ACTIVE.
1017 default=False
1018 wait_timeout (int): How long to wait until this operation is considered failed.
1019 default=300
1020 check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
1021 default=False
1022
1023 Basic Usage:
1024 >>> client = boto3.client('kinesis')
1025 >>> stream_name = 'test-stream'
1026 >>> stop_stream_encryption(client, stream_name,encryption_type, key_id)
1027
1028 Returns:
1029 Tuple (bool, bool, str, dict)
1030 """
1031 success = False
1032 changed = False
1033 err_msg = ""
1034
1035 results = dict()
1036 stream_found, stream_msg, current_stream = find_stream(client, stream_name)
1037 if stream_found:
1038 if current_stream.get("EncryptionType") == "KMS":
1039 success, err_msg = stream_encryption_action(
1040 client,
1041 stream_name,
1042 action="stop_encryption",
1043 key_id=key_id,
1044 encryption_type=encryption_type,
1045 check_mode=check_mode,
1046 )
1047 changed = success
1048 if wait:
1049 success, err_msg, results = wait_for_status(
1050 client, stream_name, "ACTIVE", wait_timeout, check_mode=check_mode
1051 )
1052 if not success:
1053 return success, True, err_msg, results
1054 err_msg = f"Kinesis Stream {stream_name} encryption stopped successfully."
1055 else:
1056 err_msg = f"Stream {stream_name} is in the process of stopping encryption."
1057 elif current_stream.get("EncryptionType") == "NONE":
1058 success = True
1059 err_msg = f"Kinesis Stream {stream_name} encryption already stopped."
1060 else:
1061 success = True
1062 changed = False
1063 err_msg = f"Stream {stream_name} does not exist."
1064
1065 if success:
1066 stream_found, stream_msg, results = find_stream(client, stream_name)
1067 tag_success, tag_msg, current_tags = get_tags(client, stream_name)
1068 if not current_tags:
1069 current_tags = dict()
1070
1071 results = camel_dict_to_snake_dict(results)
1072 results["tags"] = current_tags
1073
1074 return success, changed, err_msg, results
1075
1076
1077 def main():
1078 argument_spec = dict(
1079 name=dict(required=True),
1080 shards=dict(default=None, required=False, type="int"),
1081 retention_period=dict(default=None, required=False, type="int"),
1082 tags=dict(default=None, required=False, type="dict", aliases=["resource_tags"]),
1083 wait=dict(default=True, required=False, type="bool"),
1084 wait_timeout=dict(default=300, required=False, type="int"),
1085 state=dict(default="present", choices=["present", "absent"]),
1086 encryption_type=dict(required=False, choices=["NONE", "KMS"]),
1087 key_id=dict(required=False, type="str"),
1088 encryption_state=dict(required=False, choices=["enabled", "disabled"]),
1089 )
1090 module = AnsibleAWSModule(
1091 argument_spec=argument_spec,
1092 supports_check_mode=True,
1093 )
1094
1095 retention_period = module.params.get("retention_period")
1096 stream_name = module.params.get("name")
1097 shards = module.params.get("shards")
1098 state = module.params.get("state")
1099 tags = module.params.get("tags")
1100 wait = module.params.get("wait")
1101 wait_timeout = module.params.get("wait_timeout")
1102 encryption_type = module.params.get("encryption_type")
1103 key_id = module.params.get("key_id")
1104 encryption_state = module.params.get("encryption_state")
1105
1106 if state == "present" and not shards:
1107 module.fail_json(msg="Shards is required when state == present.")
1108
1109 if retention_period:
1110 if retention_period < 24:
1111 module.fail_json(msg="Retention period can not be less than 24 hours.")
1112
1113 check_mode = module.check_mode
1114 try:
1115 client = module.client("kinesis")
1116 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
1117 module.fail_json_aws(e, msg="Failed to connect to AWS")
1118
1119 if state == "present":
1120 success, changed, err_msg, results = create_stream(
1121 client, stream_name, shards, retention_period, tags, wait, wait_timeout, check_mode
1122 )
1123 if encryption_state == "enabled":
1124 success, changed, err_msg, results = start_stream_encryption(
1125 client, stream_name, encryption_type, key_id, wait, wait_timeout, check_mode
1126 )
1127 elif encryption_state == "disabled":
1128 success, changed, err_msg, results = stop_stream_encryption(
1129 client, stream_name, encryption_type, key_id, wait, wait_timeout, check_mode
1130 )
1131 elif state == "absent":
1132 success, changed, err_msg, results = delete_stream(client, stream_name, wait, wait_timeout, check_mode)
1133
1134 if success:
1135 module.exit_json(success=success, changed=changed, msg=err_msg, **results)
1136 else:
1137 module.fail_json(success=success, changed=changed, msg=err_msg, result=results)
1138
1139
1140 if __name__ == "__main__":
1141 main()