forked from linuxdynasty/ld-ansible-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiam_managed_policy.py
1463 lines (1316 loc) · 46.2 KB
/
iam_managed_policy.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 file is part of Ansible
#
# Ansible is 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: iam_managed_policy
short_description: Create, Modify, Delete managed IAM policies for users, groups, and roles
description:
- Allows uploading or removing IAM policies for IAM users, groups or roles.
version_added: "2.2"
requirements: [boto3, botocore]
options:
iam_type:
description:
- Type of IAM resource
required: true
default: null
choices: [ "user", "group", "role"]
iam_name:
description:
- Name of IAM resource you wish to target for policy actions. In other words, the user name, group name or role name.
required: true
policy_name:
description:
- The name label for the policy to create or remove.
required: true
policy_document:
description:
- The path to the properly json formatted policy file (mutually exclusive with C(policy_json))
required: false
policy_json:
description:
- A properly json formatted policy as string (mutually exclusive with C(policy_document), see https://github.com/ansible/ansible/issues/7005#issuecomment-42894813 on how to use it properly)
required: false
state:
description:
- Whether to create or delete the IAM policy.
required: true
default: null
choices: [ "present", "absent"]
notes:
- 'Currently boto does not support the removal of Managed Policies, the module will not work removing/adding managed policies.'
author: "Allen Sanabria (@linuxdynasty)"
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
policies:
- name: "cloudwatch"
policy: |
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:GetMetricData",
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics",
"cloudwatch:PutMetricData"
],
"Resource": [
"*"
]
}
]
}
# Create an IAM managed policy from a list of policies.
- name: Create multiple IAM managed policies
local_action:
module: iam_managed_policy
state: present
policy_name: "{{ item.name }}"
policy_json: "{{ item.policy }}"
with_items: "{{ policies }}"
# Create an S3 IAM managed policy.
- name: Create an S3 IAM Managed Policy
local_action:
module: iam_managed_policy
state: present
policy_name: "dev_s3_access"
policy_document: "dev_s3.json"
# Delete an IAM managed policy.
- name: Delete s3 IAM managed policy
local_action:
module: iam_managed_policy
state: absent
policy_name: "dev_s3_access"
'''
try:
import botocore
import boto3
import boto
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
from json import dumps, loads
import re
import datetime
from random import randint
from time import sleep
EXAMPLE_POLICY_DICT = {
"Version": "2012-10-17",
"Statement": [
{
"Action": "*",
"Resource": "*",
"Effect": "Allow",
"Sid": "Stmt1417926406000"
}
]
}
EXAMPLE_POLICY_LIST = [
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "*",
"Resource": "*",
"Effect": "Allow",
"Sid": "Stmt1417926406000"
}
]
}
]
EXAMPLE_POLICY_STR = '{"Version": "2012-10-17", "Statement": [{"Action": "*", "Resource": "*", "Effect": "Allow", "Sid": "Stmt1417926406000"}]}'
EXAMPLE_POLICY_CREATE_RESULT_LOWER_CASE = {
"policy": {
"update_date": "2016-04-02T09:00:22.911962",
"create_date": "2016-04-02T09:00:22.911953",
"description": "string",
"is_attachable": True,
"policy_name": "test",
"default_version_id": "v1",
"attachment_count": 0,
"path": "/",
"arn": "arn:aws:iam::123456789:policy/test",
"policy_id": "ANPAJDTHNXIKWXFW6P5EE"
}
}
EXAMPLE_POLICY_CREATE_RESULT = {
'Policy': {
'PolicyName': 'test',
'PolicyId': 'ANPAJDTHNXIKWXFW6P5EE',
'Arn': 'arn:aws:iam::123456789:policy/test',
'Path': '/',
'DefaultVersionId': 'v1',
'AttachmentCount': 0,
'IsAttachable': True,
'Description': 'string',
'CreateDate': datetime.datetime.now(),
'UpdateDate': datetime.datetime.now()
}
}
EXAMPLE_POLICY_RESULTS_1 = {
'Marker': 'ACUflMymIal39z7PCsx4pW3iKOWeUPqcDzRzFOnS/W26w3iNdSlU7TmWtMUG1XE9WCjeL1cSrTJ+gSLelldJp/WdoA5d6tpYVybCJQkEDTvW1A==',
'AttachedPolicies': [
{
'PolicyName': 'test1',
'PolicyArn': 'arn:aws:iam::123456789:policy/test1'
}
],
'IsTruncated': True,
'ResponseMetadata': {
'HTTPStatusCode': 200,
'RequestId': '1275fbf3-f8fb-11e5-8825-61c7f7fe1359'
}
}
EXAMPLE_POLICY_VERSION = {
'PolicyVersion': {
'Document': EXAMPLE_POLICY_STR,
'VersionId': '2012-10-17',
'IsDefaultVersion': True,
'CreateDate': datetime.datetime.now(),
},
'ResponseMetadata': {
'HTTPStatusCode': 200,
'RequestId': '1275fbf3-f8fb-11e5-8825-61c7f7fe1359'
}
}
EXAMPLE_POLICY_RESULTS_2 = {
'AttachedPolicies': [
{
'PolicyName': 'test2',
'PolicyArn': 'arn:aws:iam::123456789:policy/test2'
}
],
'IsTruncated': False,
'ResponseMetadata': {
'HTTPStatusCode': 200,
'RequestId': '1275fbf3-f8fb-11e5-8825-61c7f7fe1359'
}
}
EXAMPLE_LIST_ENTITIES_FOR_POLICY_1 = {
'PolicyGroups': [
{
'GroupName': 'test1',
'GroupId': 'arn:aws:iam::123456789:group/test1'
},
],
'PolicyUsers': [
{
'UserName': 'test1',
'UserId': 'arn:aws:iam::123456789:user/test1'
},
],
'PolicyRoles': [
{
'RoleName': 'test1',
'RoleId': 'arn:aws:iam::123456789:role/test1'
},
],
'IsTruncated': True,
'Marker': 'ACUflMymIal39z7PCsx4pW3iKOWeUPqcDzRzFOnS/W26w3iNdSlU7TmWtMUG1XE9WCjeL1cSrTJ+gSLelldJp/WdoA5d6tpYVybCJQkEDTvW1A==',
}
EXAMPLE_LIST_ENTITIES_FOR_POLICY_2 = {
'PolicyGroups': [
{
'GroupName': 'test2',
'GroupId': 'arn:aws:iam::123456789:group/test2'
},
],
'PolicyUsers': [
{
'UserName': 'test2',
'UserId': 'arn:aws:iam::123456789:user/test2'
},
],
'PolicyRoles': [
{
'RoleName': 'test2',
'RoleId': 'arn:aws:iam::123456789:role/test2'
},
],
'IsTruncated': False,
}
EXAMPLE_LIST_POLICIES = {
'Policies': [
{
'PolicyName': 'test',
'PolicyId': 'ANPAJDTHNXIKWXFW6P5EE',
'Arn': 'arn:aws:iam::123456789:policy/test',
'Path': '/',
'DefaultVersionId': 'v1',
'AttachmentCount': 0,
'IsAttachable': True,
'Description': 'string',
'CreateDate': datetime.datetime.now(),
'UpdateDate': datetime.datetime.now()
}
],
'IsTruncated': False,
}
EXAMPLE_LIST_POLICY_VERSIONS = {
'Versions': [
{
'Document': 'string',
'VersionId': 'v1',
'IsDefaultVersion': False,
'CreateDate': datetime.datetime.now()
},
],
'IsTruncated': False
}
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 validate_json(policy_json, is_file=False):
"""Validate and convert to json if needed.
Args:
policy_json (str|dict): String representing the file path to the json
document or a string representing the json or a dict to be converted
into json.
Kwargs:
is_file (bool): If this is set to true, this function will try to
open policy_json and validate or convert to json.
Basic Usage:
>>> policy_json = '{"Version": "2012-10-17", "Statement": [{"Action": "*", "Resource": "*", "Effect": "Allow", "Sid": "Stmt1417926406000"}]}'
>>> policy, err_msg = validate_json(policy_json)
"""
err_msg = ''
policy = None
if is_file:
try:
policy = dumps(loads(open(policy_json, 'r').read()))
except Exception as e:
err_msg = (
'Failed to convert the policy into valid JSON: {0}'
.format(str(e))
)
else:
if isinstance(policy_json, dict):
try:
policy = dumps(policy_json)
except Exception as e:
err_msg = (
'Failed to convert the policy into valid JSON: {0}'
.format(str(e))
)
elif isinstance(policy_json, basestring):
try:
policy = dumps(eval(policy_json))
except Exception as e:
err_msg = (
'Failed to convert the policy into valid JSON: {0}'
.format(str(e))
)
else:
err_msg = (
'Policy is not a valid dict or string: {0}'
.format(type(policy_json))
)
return policy, err_msg
def get_policy(client, policy_arn, check_mode=False):
"""Retrieve an IAM Managed Policy.
Args:
client (botocore.client.EC2): Boto3 client.
policy_arn (str): The Amazon resource identifier.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> policy_arn = 'arn:aws:iam::123456789:policy/test'
>>> get_policy(client, policy_arn)
Returns:
Tuple (bool, str, dict)
"""
success = False
err_msg = ''
params = {
'PolicyArn': policy_arn,
}
policy = dict()
try:
if not check_mode:
policy = client.get_policy(**params)['Policy']
success = True
else:
if policy_arn == 'arn:aws:iam::123456789:policy/test':
policy = EXAMPLE_POLICY_CREATE_RESULT
success = True
else:
success = False
err_msg = (
'An error occurred (NoSuchEntity) when calling the ListPolicies operation: {0} does not exist.'
.format(policy_name)
)
return success, err_msg, policy
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, policy
def get_policy_version(client, policy_arn, version_id, check_mode=False):
"""Retrieve an IAM Managed Policy.
Args:
client (botocore.client.EC2): Boto3 client.
policy_arn (str): The Amazon resource identifier.
version_id (str): The version of the policy.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> policy_arn = 'arn:aws:iam::123456789:policy/test'
>>> version_id = 'v1'
>>> get_policy_version(client, policy_arn, version_id)
Returns:
Tuple (bool, str, dict)
"""
success = False
err_msg = ''
params = {
'PolicyArn': policy_arn,
'VersionId': version_id
}
policy = dict()
try:
if not check_mode:
policy = client.get_policy_version(**params)['PolicyVersion']
success = True
else:
if policy_arn == 'arn:aws:iam::123456789:policy/test':
policy = EXAMPLE_POLICY_VERSION['PolicyVersion']
success = True
else:
success = False
err_msg = (
'An error occurred (NoSuchEntity) when calling the ListPolicies operation: {0} does not exist.'
.format(policy_name)
)
return success, err_msg, policy
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, policy
def find_policy(client, policy_name, check_mode=False):
"""Retrieve an IAM Managed Policy.
Args:
client (botocore.client.EC2): Boto3 client.
policy_name (str): Name of the managed policy you are retrieving.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> policy_name = 'test'
>>> find_policy(client, policy_name)
Returns:
Tuple (bool, str, dict)
"""
success = False
err_msg = ''
params = {
'Scope': 'Local'
}
result = dict()
try:
is_truncated = True
i = 0
marker = None
policies = dict()
while is_truncated:
if i > 0:
params['Marker'] = marker
if not check_mode:
policies = client.list_policies(**params)
for policy in policies['Policies']:
if policy['PolicyName'] == policy_name:
result = policy
success = True
err_msg = '{0} policy found.'.format(policy_name)
return success, err_msg, result
else:
if policy_name == 'test':
policies = EXAMPLE_LIST_POLICIES
success = True
else:
success = False
err_msg = (
'An error occurred (NoSuchEntity) when calling the ListPolicies operation: {0} does not exist.'
.format(policy_name)
)
return success, err_msg, result
is_truncated = policies['IsTruncated']
if is_truncated:
i += 1
marker = policies.get('Marker', None)
sleep(randint(1,2))
success = True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, result
def list_attached_policies(client, resource_name, resource_type, check_mode=False):
"""List all attached policies to a resource (group, user, role).
Args:
client (botocore.client.EC2): Boto3 client.
resource_name (str): Name of the resource you are listing policies for.
resource_type (str): group, user, or role.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> resource_name = 'admin'
>>> resource_type = 'role'
>>> list_attached_policies(client, resource_name, resource_type)
Returns:
Tuple (bool, str, dict)
"""
err_msg = ''
success = False
results = list()
actions = {
'user': client.list_attached_user_policies,
'group': client.list_attached_group_policies,
'role': client.list_attached_role_policies,
}
params = {
'{0}Name'.format(resource_type.capitalize()): resource_name
}
if resource_type != 'user' and resource_type != 'group' and resource_type != 'role':
err_msg = 'Invalid resource type {0}'.format(resource_type)
return success, err_msg, results
try:
is_truncated = True
i = 0
marker = None
policies = dict()
while is_truncated:
if i > 0:
params['Marker'] = marker
if not check_mode:
policies = actions[resource_type](**params)
else:
if resource_name == 'test':
if i == 0:
policies = EXAMPLE_POLICY_RESULTS_1
else:
policies = EXAMPLE_POLICY_RESULTS_2
success = True
else:
success = False
err_msg = (
'An error occurred (NoSuchEntity) when calling the ListAttachedRolePolicies operation: {0} {1} does not exist.'
.format(resource_type.capitalize(), resource_name)
)
return success, err_msg, results
is_truncated = policies['IsTruncated']
results.extend(policies['AttachedPolicies'])
if is_truncated:
i += 1
marker = policies.get('Marker', None)
sleep(randint(1,2))
success = True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, results
def list_policy_versions(client, policy_arn, check_mode=False):
"""List all versions for an IAM Policy.
Args:
client (botocore.client.EC2): Boto3 client.
policy_arn (str): The Amazon resource identifier.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> policy_arn = 'arn:aws:iam::123456789:policy/test'
>>> list_policy_versions(client, policy_arn)
Returns:
Tuple (bool, str, dict)
"""
err_msg = ''
success = False
params = {
'PolicyArn': policy_arn,
}
policy_versions = list()
try:
is_truncated = True
i = 0
marker = None
versions = dict()
while is_truncated:
if i > 0:
params['Marker'] = marker
if not check_mode:
versions = client.list_policy_versions(**params)
else:
if policy_arn[-4:] == 'test':
versions = EXAMPLE_LIST_POLICY_VERSIONS
success = True
else:
success = False
err_msg = (
'An error occurred (NoSuchEntity) when calling the ListPolicyVersions operation: ARN {0} is not valid.'
.format(policy_arn)
)
return success, err_msg, policy_versions
is_truncated = versions['IsTruncated']
policy_versions.extend(versions['Versions'])
if is_truncated:
i += 1
marker = versions.get('Marker', None)
sleep(randint(1,2))
success = True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, policy_versions
def list_entities_for_policy(client, policy_arn, check_mode=False):
"""List all entities for an IAM Policy. This will list every role, user,
and group that has this policy attached.
Args:
client (botocore.client.EC2): Boto3 client.
policy_arn (str): The Amazon resource identifier.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> policy_arn = 'arn:aws:iam::123456789:policy/test'
>>> list_entities_for_policy(client, policy_arn)
Returns:
Tuple (bool, str, dict)
"""
err_msg = ''
success = False
groups = list()
users = list()
roles = list()
params = {
'PolicyArn': policy_arn,
}
try:
is_truncated = True
i = 0
marker = None
entities = dict()
while is_truncated:
if i > 0:
params['Marker'] = marker
if not check_mode:
entities = client.list_entities_for_policy(**params)
else:
if policy_arn[-4:] == 'test':
if i == 0:
entities = EXAMPLE_LIST_ENTITIES_FOR_POLICY_1
else:
entities = EXAMPLE_LIST_ENTITIES_FOR_POLICY_2
success = True
else:
success = False
err_msg = (
'An error occurred (NoSuchEntity) when calling the ListEntitiesForPolicy operation: ARN {0} is not valid.'
.format(policy_arn)
)
return success, err_msg, users, groups, roles
is_truncated = entities['IsTruncated']
groups.extend(entities['PolicyGroups'])
users.extend(entities['PolicyUsers'])
roles.extend(entities['PolicyRoles'])
if is_truncated:
i += 1
marker = entities.get('Marker', None)
sleep(randint(1,2))
success = True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg, users, groups, roles
def policy_action(client, policy_name=None, policy_arn=None, policy_json=None,
policy_path='/', description='', version=None,
action='create', check_mode=False):
"""Create or Delete an IAM Managed Policy
Args:
client (botocore.client.EC2): Boto3 client.
Kwargs:
policy_name (str): The name of the IAM Managed POlicy.
policy_arn (str): The Amazon resource identifier. This is needed when
you are going to delete a policy.
policy_json (str): A valid json string that contains the IAM policy.
description (str): Description of this policy
version (str): The version of the policy.
action (str): The action to perform.
valid actions == create and delete and create_version and delete_version
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('iam')
>>> policy_name = 'test'
>>> policy_json = '{"Version": "2012-10-17", "Statement": [{"Action": "*", "Resource": "*", "Effect": "Allow", "Sid": "Stmt1417926406000"}]}'
>>> description = 'Test Policy'
>>> policy_action(client, policy_name=policy_name, policy_json=policy_json,description=description, action='create')
Returns:
List (bool, str)
"""
success = False
err_msg = ''
actions = {
'create': {
'params': {
'PolicyName': policy_name,
'Path': policy_path,
'PolicyDocument': policy_json,
'Description': description
},
'run': client.create_policy
},
'create_version': {
'params': {
'PolicyArn': policy_arn,
'PolicyDocument': policy_json,
'SetAsDefault': True
},
'run': client.create_policy_version
},
'delete': {
'params': {
'PolicyArn': policy_arn,
},
'run': client.delete_policy
},
'delete_version': {
'params': {
'PolicyArn': policy_arn,
'VersionId': version
},
'run': client.delete_policy_version
},
}
if action == 'create':
if not policy_name or not policy_json:
err_msg = 'Missing parameters for action create: policy_name and policy_json must be set'
return success, err_msg
elif action == 'create_version':
if not policy_arn or not policy_json:
err_msg = 'Missing parameters for action create_version: policy_arn and policy_json must be set'
return success, err_msg
elif action == 'delete':
if not policy_arn:
err_msg = 'Missing parameters for action delete: policy_arn must be set'
return success, err_msg
elif action == 'delete_version':
if not policy_arn or not version:
err_msg = 'Missing parameters for action delete: policy_arn and version must be set'
return success, err_msg
else:
err_msg = 'Invalid action {0}'.format(action)
return success, err_msg, dict()
try:
if not check_mode:
actions[action]['run'](**actions[action]['params'])
success = True
else:
success = True
err_msg = '{0} succeded'.format('action')
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg
def resource_action(client, resource_name, resource_type, policy_arn,
action='attach', check_mode=False):
"""Create or Delete an IAM Managed Policy
Args:
client (botocore.client.EC2): Boto3 client.
resource_name (str): The name of the resource that is being attached to the policy.
resource_type (str): group, user, or role.
policy_arn (str): The Amazon resource identifier. This is needed when
you are going to delete a policy.
Kwargs:
action (str): The action to perform.
valid actions == attach and detach
default=attach
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> resource_name = 'admin'
>>> resource_type = 'role'
>>> policy_arn = 'arn:aws:iam::123456789:policy/test'
>>> resource_action(client, resource_name, resource_type, policy_arn)
Returns:
List (bool, str)
"""
success = False
err_msg = ''
resources = {
'user': {
'attach': client.attach_user_policy,
'detach': client.detach_user_policy,
},
'group': {
'attach': client.attach_group_policy,
'detach': client.detach_group_policy,
},
'role': {
'attach': client.attach_role_policy,
'detach': client.detach_role_policy,
}
}
params = {
'PolicyArn': policy_arn,
'{0}Name'.format(resource_type.capitalize()): resource_name
}
if action != 'attach' and action != 'detach':
err_msg = 'Invalid action {0}'.format(action)
return success, err_msg
if resource_type != 'user' and resource_type != 'group' and resource_type != 'role':
err_msg = 'Invalid resource type {0}'.format(resource_type)
return success, err_msg
try:
if not check_mode:
resources[resource_type][action](**params)
success = True
else:
success = True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
return success, err_msg
def attach(client, policy_arn, resource_name, resource_type, check_mode=False):
"""Attach an IAM Managed Policy to an IAM Resource (Role, User, Group).
Args:
client (botocore.client.EC2): Boto3 client.
policy_arn (str): The Amazon resource identifier.
resource_name (str): The name of the resource that is being attached to the policy.
resource_type (str): group, user, or role.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> policy_arn = 'arn:aws:iam::123456789:policy/test'
>>> resource_name = 'admin'
>>> resource_type = 'role'
>>> attach(client, resource_name, resource_type)
Returns:
List (bool, bool, str)
"""
success = False
changed = False
err_msg = ''
success, err_msg, policies = (
list_attached_policies(
client, resource_name, resource_type, check_mode=check_mode
)
)
if success:
policy_exist_in_resource = False
if len(policies) > 0:
for policy in policies:
if policy['PolicyArn'] == policy_arn:
policy_exist_in_resource = True
success = True
break
if not policy_exist_in_resource:
success, err_msg = (
resource_action(
client, resource_name, resource_type, policy_arn,
action='attach', check_mode=check_mode
)
)
if success:
changed = True
return success, changed, err_msg
def delete_policy_versions(client, policy_arn, except_version=None,
check_mode=False):
"""Delete all versions of a policy, except the default one.
Args:
client (botocore.client.EC2): Boto3 client.
policy_arn (str): The Amazon resource identifier.
Kwargs:
except_version (str): Version you want to keep.
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('iam')
>>> policy_arn = 'arn:aws:iam::123456789:policy/test'
>>> delete_policy_versions(client, policy_arn)
Returns:
List (bool, bool, str)
"""
success = False
changed = False
err_msg = ''
success, err_msg, policy_versions = (
list_policy_versions(client, policy_arn, check_mode)
)
versions_deleted = 0
if not except_version:
except_version = ''
if success:
if policy_versions: