forked from linuxdynasty/ld-ansible-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkinesis_stream.py
1065 lines (963 loc) · 33.5 KB
/
kinesis_stream.py
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: kinesis_stream
short_description: Manage a Kinesis Stream.
description:
- Create or Delete a Kinesis Stream.
- Update the retention period of a Kinesis Stream.
- Update Tags on a Kinesis Stream.
version_added: "2.2"
author: Allen Sanabria (@linuxdynasty)
options:
name:
description:
- "The name of the Kinesis Stream you are managing."
default: None
required: true
shards:
description:
- "The number of shards you want to have with this stream. This can not
be modified after being created."
- "This is required when state == present"
required: false
default: None
retention_period:
description:
- "The default retention period is 24 hours and can not be less than 24
hours."
- "The retention period can be modified during any point in time."
required: false
default: None
state:
description:
- "Create or Delete the Kinesis Stream."
required: false
default: present
choices: [ 'present', 'absent' ]
wait:
description:
- Wait for operation to complete before returning
required: false
default: true
wait_timeout:
description:
- How many seconds to wait for an operation to complete before timing out
required: false
default: 300
tags:
description:
- "A dictionary of resource tags of the form: { tag1: value1, tag2: value2 }."
required: false
default: null
aliases: [ "resource_tags" ]
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
# Basic creation example:
- name: Set up Kinesis Stream with 10 shards and wait for the stream to become ACTIVE
kinesis_stream:
name: test-stream
shards: 10
wait: yes
wait_timeout: 600
register: test_stream
# Basic creation example with tags:
- name: Set up Kinesis Stream with 10 shards, tag the environment, and wait for the stream to become ACTIVE
kinesis_stream:
name: test-stream
shards: 10
tags:
Env: development
wait: yes
wait_timeout: 600
register: test_stream
# Basic creation example with tags and increase the retention period from the default 24 hours to 48 hours:
- name: Set up Kinesis Stream with 10 shards, tag the environment, increase the retention period and wait for the stream to become ACTIVE
kinesis_stream:
name: test-stream
retention_period: 48
shards: 10
tags:
Env: development
wait: yes
wait_timeout: 600
register: test_stream
# Basic delete example:
- name: Delete Kinesis Stream test-stream and wait for it to finish deleting.
kinesis_stream:
name: test-stream
state: absent
wait: yes
wait_timeout: 600
register: test_stream
'''
RETURN = '''
stream_name:
description: The name of the Kinesis Stream.
returned: when state == present.
type: string
sample: "test-stream"
stream_arn:
description: The amazon resource identifier
returned: when state == present.
type: string
sample: "arn:aws:kinesis:east-side:123456789:stream/test-stream"
stream_status:
description: The current state of the Kinesis Stream.
returned: when state == present.
type: string
sample: "ACTIVE"
retention_period_hours:
description: Number of hours messages will be kept for a Kinesis Stream.
returned: when state == present.
type: int
sample: 24
tags:
description: Dictionary containing all the tags associated with the Kinesis stream.
returned: when state == present.
type: dict
sample: {
"Name": "Splunk",
"Env": "development"
}
'''
try:
import botocore
import boto3
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
import re
import datetime
import time
from functools import reduce
def convert_to_lower(data):
"""Convert all uppercase keys in dict with lowercase_
Args:
data (dict): Dictionary with keys that have upper cases in them
Example.. FooBar == foo_bar
if a val is of type datetime.datetime, it will be converted to
the ISO 8601
Basic Usage:
>>> test = {'FooBar': []}
>>> test = convert_to_lower(test)
{
'foo_bar': []
}
Returns:
Dictionary
"""
results = dict()
if isinstance(data, dict):
for key, val in data.items():
key = re.sub(r'(([A-Z]{1,3}){1})', r'_\1', key).lower()
if key[0] == '_':
key = key[1:]
if isinstance(val, datetime.datetime):
results[key] = val.isoformat()
elif isinstance(val, dict):
results[key] = convert_to_lower(val)
elif isinstance(val, list):
converted = list()
for item in val:
converted.append(convert_to_lower(item))
results[key] = converted
else:
results[key] = val
return results
def make_tags_in_proper_format(tags):
"""Take a dictionary of tags and convert them into the AWS Tags format.
Args:
tags (list): The tags you want applied.
Basic Usage:
>>> tags = [{'Key': 'env', 'Value': 'development'}]
>>> make_tags_in_proper_format(tags)
{
"env": "development",
}
Returns:
Dict
"""
formatted_tags = dict()
for tag in tags:
formatted_tags[tag.get('Key')] = tag.get('Value')
return formatted_tags
def make_tags_in_aws_format(tags):
"""Take a dictionary of tags and convert them into the AWS Tags format.
Args:
tags (dict): The tags you want applied.
Basic Usage:
>>> tags = {'env': 'development', 'service': 'web'}
>>> make_tags_in_proper_format(tags)
[
{
"Value": "web",
"Key": "service"
},
{
"Value": "development",
"key": "env"
}
]
Returns:
List
"""
formatted_tags = list()
for key, val in tags.items():
formatted_tags.append({
'Key': key,
'Value': val
})
return formatted_tags
def get_tags(client, stream_name, check_mode=False):
"""Retrieve the tags for a Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client.
stream_name (str): Name of the Kinesis stream.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> stream_name = 'test-stream'
>> get_tags(client, stream_name)
Returns:
Tuple (bool, str, dict)
"""
err_msg = ''
success = False
params = {
'StreamName': stream_name,
}
results = dict()
try:
if not check_mode:
results = (
client.list_tags_for_stream(**params)['Tags']
)
else:
results = [
{
'Key': 'DryRunMode',
'Value': 'true'
},
]
success = True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, results
def find_stream(client, stream_name, limit=1, check_mode=False):
"""Retrieve a Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client.
stream_name (str): Name of the Kinesis stream.
Kwargs:
limit (int): Limit the number of shards to return within a stream.
default=1
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> stream_name = 'test-stream'
Returns:
Tuple (bool, str, dict)
"""
err_msg = ''
success = False
params = {
'StreamName': stream_name,
'Limit': limit
}
results = dict()
try:
if not check_mode:
results = (
client.describe_stream(**params)['StreamDescription']
)
results.pop('Shards')
else:
results = {
'HasMoreShards': True,
'RetentionPeriodHours': 24,
'StreamName': stream_name,
'StreamARN': 'arn:aws:kinesis:east-side:123456789:stream/{0}'.format(stream_name),
'StreamStatus': 'ACTIVE'
}
success = True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, results
def wait_for_status(client, stream_name, status, wait_timeout=300,
check_mode=False):
"""Wait for the the status to change for a Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client
stream_name (str): The name of the kinesis stream.
status (str): The status to wait for.
examples. status=available, status=deleted
Kwargs:
wait_timeout (int): Number of seconds to wait, until this timeout is reached.
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> stream_name = 'test-stream'
>>> wait_for_status(client, stream_name, 'ACTIVE', 300)
Returns:
Tuple (bool, str, dict)
"""
polling_increment_secs = 5
wait_timeout = time.time() + wait_timeout
status_achieved = False
stream = dict()
err_msg = ""
while wait_timeout > time.time():
try:
find_success, find_msg, stream = (
find_stream(client, stream_name, check_mode=check_mode)
)
if check_mode:
status_achieved = True
break
elif status != 'DELETING':
if find_success and stream:
if stream.get('StreamStatus') == status:
status_achieved = True
break
elif status == 'DELETING' and not check_mode:
if not find_success:
status_achieved = True
break
else:
time.sleep(polling_increment_secs)
except botocore.exceptions.ClientError as e:
err_msg = str(e)
if not status_achieved:
err_msg = "Wait time out reached, while waiting for results"
return status_achieved, err_msg, stream
def tags_action(client, stream_name, tags, action='create', check_mode=False):
"""Create or delete multiple tags from a Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client.
resource_id (str): The Amazon resource id.
tags (list): List of dictionaries.
examples.. [{Name: "", Values: [""]}]
Kwargs:
action (str): The action to perform.
valid actions == create and delete
default=create
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> resource_id = 'pcx-123345678'
>>> tags = {'env': 'development'}
>>> update_tags(client, resource_id, tags)
[True, '']
Returns:
List (bool, str)
"""
success = False
err_msg = ""
params = {'StreamName': stream_name}
try:
if not check_mode:
if action == 'create':
params['Tags'] = tags
client.add_tags_to_stream(**params)
success = True
elif action == 'delete':
params['TagKeys'] = tags.keys()
client.remove_tags_from_stream(**params)
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
else:
if action == 'create':
success = True
elif action == 'delete':
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg
def recreate_tags_from_list(list_of_tags):
"""Recreate tags from a list of tuples into the Amazon Tag format.
Args:
list_of_tags (list): List of tuples.
Basic Usage:
>>> list_of_tags = [('Env', 'Development')]
>>> recreate_tags_from_list(list_of_tags)
[
{
"Value": "Development",
"Key": "Env"
}
]
Returns:
List
"""
tags = list()
i = 0
list_of_tags = list_of_tags
for i in range(len(list_of_tags)):
key_name = list_of_tags[i][0]
key_val = list_of_tags[i][1]
tags.append(
{
'Key': key_name,
'Value': key_val
}
)
return tags
def update_tags(client, stream_name, tags, check_mode=False):
"""Update tags for an amazon resource.
Args:
resource_id (str): The Amazon resource id.
tags (dict): Dictionary of tags you want applied to the Kinesis stream.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> stream_name = 'test-stream'
>>> tags = {'env': 'development'}
>>> update_tags(client, stream_name, tags)
[True, '']
Return:
Tuple (bool, str)
"""
success = False
err_msg = ''
tag_success, tag_msg, current_tags = (
get_tags(client, stream_name, check_mode=check_mode)
)
if current_tags:
tags = make_tags_in_aws_format(tags)
current_tags_set = (
set(
reduce(
lambda x, y: x + y,
[make_tags_in_proper_format(current_tags).items()]
)
)
)
new_tags_set = (
set(
reduce(
lambda x, y: x + y,
[make_tags_in_proper_format(tags).items()]
)
)
)
tags_to_delete = list(current_tags_set.difference(new_tags_set))
tags_to_update = list(new_tags_set.difference(current_tags_set))
if tags_to_delete:
tags_to_delete = make_tags_in_proper_format(
recreate_tags_from_list(tags_to_delete)
)
delete_success, delete_msg = (
tags_action(
client, stream_name, tags_to_delete, action='delete',
check_mode=check_mode
)
)
if not delete_success:
return delete_success, delete_msg
if tags_to_update:
tags = make_tags_in_proper_format(
recreate_tags_from_list(tags_to_update)
)
else:
return True, 'Tags do not need to be updated'
if tags:
create_success, create_msg = (
tags_action(
client, stream_name, tags, action='create',
check_mode=check_mode
)
)
return create_success, create_msg
return success, err_msg
def stream_action(client, stream_name, shard_count=1, action='create',
timeout=300, check_mode=False):
"""Create or Delete an Amazon Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client.
stream_name (str): The name of the kinesis stream.
Kwargs:
shard_count (int): Number of shards this stream will use.
action (str): The action to perform.
valid actions == create and delete
default=create
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> stream_name = 'test-stream'
>>> shard_count = 20
>>> stream_action(client, stream_name, shard_count, action='create')
Returns:
List (bool, str)
"""
success = False
err_msg = ''
params = {
'StreamName': stream_name
}
try:
if not check_mode:
if action == 'create':
params['ShardCount'] = shard_count
client.create_stream(**params)
success = True
elif action == 'delete':
client.delete_stream(**params)
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
else:
if action == 'create':
success = True
elif action == 'delete':
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg
def retention_action(client, stream_name, retention_period=24,
action='increase', check_mode=False):
"""Increase or Decreaste the retention of messages in the Kinesis stream.
Args:
client (botocore.client.EC2): Boto3 client.
stream_name (str): The
Kwargs:
retention_period (int): This is how long messages will be kept before
they are discarded. This can not be less than 24 hours.
action (str): The action to perform.
valid actions == create and delete
default=create
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> stream_name = 'test-stream'
>>> retention_period = 48
>>> stream_action(client, stream_name, retention_period, action='create')
Returns:
Tuple (bool, str)
"""
success = False
err_msg = ''
params = {
'StreamName': stream_name
}
try:
if not check_mode:
if action == 'increase':
params['RetentionPeriodHours'] = retention_period
client.increase_stream_retention_period(**params)
success = True
elif action == 'decrease':
params['RetentionPeriodHours'] = retention_period
client.decrease_stream_retention_period(**params)
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
else:
if action == 'increase':
success = True
elif action == 'decrease':
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg
def update(client, current_stream, stream_name, retention_period=None,
tags=None, wait=False, wait_timeout=300, check_mode=False):
"""Update an Amazon Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client.
stream_name (str): The name of the kinesis stream.
Kwargs:
retention_period (int): This is how long messages will be kept before
they are discarded. This can not be less than 24 hours.
tags (dict): The tags you want applied.
wait (bool): Wait until Stream is ACTIVE.
default=False
wait_timeout (int): How long to wait until this operation is considered failed.
default=300
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> current_stream = {
'HasMoreShards': True,
'RetentionPeriodHours': 24,
'StreamName': 'test-stream',
'StreamARN': 'arn:aws:kinesis:us-west-2:123456789:stream/test-stream',
'StreamStatus': "ACTIVE'
}
>>> stream_name = 'test-stream'
>>> retention_period = 48
>>> stream_action(client, current_stream, stream_name,
retention_period, action='create' )
Returns:
Tuple (bool, bool, str)
"""
success = False
changed = False
err_msg = ''
if retention_period:
if wait:
wait_success, wait_msg, current_stream = (
wait_for_status(
client, stream_name, 'ACTIVE', wait_timeout,
check_mode=check_mode
)
)
if not wait_success:
return wait_success, True, wait_msg
if current_stream['StreamStatus'] == 'ACTIVE':
if retention_period > current_stream['RetentionPeriodHours']:
retention_changed, retention_msg = (
retention_action(
client, stream_name, retention_period, action='increase',
check_mode=check_mode
)
)
if retention_changed:
success = True
elif retention_period < current_stream['RetentionPeriodHours']:
retention_changed, retention_msg = (
retention_action(
client, stream_name, retention_period, action='decrease',
check_mode=check_mode
)
)
if retention_changed:
success = True
elif retention_period == current_stream['RetentionPeriodHours']:
retention_changed = False
retention_msg = (
'Retention {0} is the same as {1}'
.format(
retention_period,
current_stream['RetentionPeriodHours']
)
)
success = True
changed = retention_changed
err_msg = retention_msg
if changed and wait:
wait_success, wait_msg, current_stream = (
wait_for_status(
client, stream_name, 'ACTIVE', wait_timeout,
check_mode=check_mode
)
)
if not wait_success:
return wait_success, True, wait_msg
elif changed and not wait:
stream_found, stream_msg, current_stream = (
find_stream(client, stream_name, check_mode=check_mode)
)
if stream_found:
if current_stream['StreamStatus'] != 'ACTIVE':
err_msg = (
'Retention Period for {0} is in the process of updating'
.format(stream_name)
)
return success, changed, err_msg
else:
err_msg = (
'StreamStatus has to be ACTIVE in order to modify the retention period. Current status is {0}'
.format(current_stream['StreamStatus'])
)
return success, changed, err_msg
if tags:
changed, err_msg = (
update_tags(client, stream_name, tags, check_mode=check_mode)
)
if changed:
success = True
if wait:
success, err_msg, _ = (
wait_for_status(
client, stream_name, 'ACTIVE', wait_timeout,
check_mode=check_mode
)
)
if success and changed:
err_msg = 'Kinesis Stream {0} updated successfully.'.format(stream_name)
elif success and not changed:
err_msg = 'Kinesis Stream {0} did not changed.'.format(stream_name)
return success, changed, err_msg
def create_stream(client, stream_name, number_of_shards=1, retention_period=None,
tags=None, wait=False, wait_timeout=300, check_mode=False):
"""Create an Amazon Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client.
stream_name (str): The name of the kinesis stream.
Kwargs:
number_of_shards (int): Number of shards this stream will use.
default=1
retention_period (int): Can not be less than 24 hours
default=None
tags (dict): The tags you want applied.
default=None
wait (bool): Wait until Stream is ACTIVE.
default=False
wait_timeout (int): How long to wait until this operation is considered failed.
default=300
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> stream_name = 'test-stream'
>>> number_of_shards = 10
>>> tags = {'env': 'test'}
>>> create_stream(client, stream_name, number_of_shards, tags=tags)
Returns:
Tuple (bool, bool, str, dict)
"""
success = False
changed = False
err_msg = ''
results = dict()
stream_found, stream_msg, current_stream = (
find_stream(client, stream_name, check_mode=check_mode)
)
if stream_found and current_stream['StreamStatus'] == 'DELETING' and wait:
wait_success, wait_msg, current_stream = (
wait_for_status(
client, stream_name, 'ACTIVE', wait_timeout,
check_mode=check_mode
)
)
if stream_found and current_stream['StreamStatus'] != 'DELETING':
success, changed, err_msg = update(
client, current_stream, stream_name, retention_period, tags,
wait, wait_timeout, check_mode=check_mode
)
else:
create_success, create_msg = (
stream_action(
client, stream_name, number_of_shards, action='create',
check_mode=check_mode
)
)
if create_success:
changed = True
if wait:
wait_success, wait_msg, results = (
wait_for_status(
client, stream_name, 'ACTIVE', wait_timeout,
check_mode=check_mode
)
)
err_msg = (
'Kinesis Stream {0} is in the process of being created'
.format(stream_name)
)
if not wait_success:
return wait_success, True, wait_msg, results
else:
err_msg = (
'Kinesis Stream {0} created successfully'
.format(stream_name)
)
if tags:
changed, err_msg = (
tags_action(
client, stream_name, tags, action='create',
check_mode=check_mode
)
)
if changed:
success = True
if not success:
return success, changed, err_msg, results
stream_found, stream_msg, current_stream = (
find_stream(client, stream_name, check_mode=check_mode)
)
if retention_period and current_stream['StreamStatus'] == 'ACTIVE':
changed, err_msg = (
retention_action(
client, stream_name, retention_period, action='increase',
check_mode=check_mode
)
)
if changed:
success = True
if not success:
return success, changed, err_msg, results
else:
err_msg = (
'StreamStatus has to be ACTIVE in order to modify the retention period. Current status is {0}'
.format(current_stream['StreamStatus'])
)
success = create_success
changed = True
if success:
_, _, results = (
find_stream(client, stream_name, check_mode=check_mode)
)
_, _, current_tags = (
get_tags(client, stream_name, check_mode=check_mode)
)
if current_tags and not check_mode:
current_tags = make_tags_in_proper_format(current_tags)
results['Tags'] = current_tags
elif check_mode and tags:
results['Tags'] = tags
else:
results['Tags'] = dict()
results = convert_to_lower(results)
return success, changed, err_msg, results
def delete_stream(client, stream_name, wait=False, wait_timeout=300,
check_mode=False):
"""Delete an Amazon Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client.
stream_name (str): The name of the kinesis stream.
Kwargs:
wait (bool): Wait until Stream is ACTIVE.
default=False
wait_timeout (int): How long to wait until this operation is considered failed.
default=300
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('kinesis')
>>> stream_name = 'test-stream'
>>> delete_stream(client, stream_name)
Returns:
Tuple (bool, bool, str, dict)
"""
success = False
changed = False
err_msg = ''
results = dict()
stream_found, stream_msg, current_stream = (
find_stream(client, stream_name, check_mode=check_mode)
)
if stream_found:
success, err_msg = (
stream_action(
client, stream_name, action='delete', check_mode=check_mode
)
)
if success:
changed = True
if wait:
success, err_msg, results = (
wait_for_status(
client, stream_name, 'DELETING', wait_timeout,
check_mode=check_mode
)
)
err_msg = 'Stream {0} deleted successfully'.format(stream_name)
if not success:
return success, True, err_msg, results
else:
err_msg = (
'Stream {0} is in the process of being deleted'
.format(stream_name)
)
else:
success = True
changed = False
err_msg = 'Stream {0} does not exist'.format(stream_name)
return success, changed, err_msg, results
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
name = dict(default=None, required=True),
shards = dict(default=None, required=False, type='int'),
retention_period = dict(default=None, required=False, type='int'),
tags = dict(default=None, required=False, type='dict', aliases=['resource_tags']),
wait = dict(default=True, required=False, type='bool'),
wait_timeout = dict(default=300, required=False, type='int'),
state = dict(default='present', choices=['present', 'absent']),
)
)
module = AnsibleModule(
argument_spec=argument_spec,