Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/iam_managed_policy.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: iam_managed_policy
10 version_added: 1.0.0
11 version_added_collection: community.aws
12 short_description: Manage User Managed IAM policies
13 description:
14 - Allows creating and removing managed IAM policies.
15 options:
16 name:
17 description:
18 - The name of the managed policy.
19 - >-
20 Note: Policy names are unique within an account. Paths (O(path)) do B(not) affect
21 the uniqueness requirements of O(name). For example it is not permitted to have both
22 C(/Path1/MyPolicy) and C(/Path2/MyPolicy) in the same account.
23 - The parameter was renamed from O(policy_name) to O(name) in release 7.2.0.
24 required: true
25 type: str
26 aliases: ["policy_name"]
27 path:
28 description:
29 - The path for the managed policy.
30 - For more information about IAM paths, see the AWS IAM identifiers documentation
31 U(https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html).
32 aliases: ['prefix', 'path_prefix']
33 required: false
34 type: str
35 version_added: 7.2.0
36 description:
37 description:
38 - A helpful description of this policy, this value is immutable and only set when creating a new policy.
39 - The parameter was renamed from O(policy_description) to O(description) in release 7.2.0.
40 aliases: ["policy_description"]
41 type: str
42 policy:
43 description:
44 - A properly json formatted policy
45 type: json
46 make_default:
47 description:
48 - Make this revision the default revision.
49 default: true
50 type: bool
51 only_version:
52 description:
53 - Remove all other non default revisions, if this is used with O(make_default) it will result in all other versions of this policy being deleted.
54 type: bool
55 default: false
56 state:
57 description:
58 - Should this managed policy be present or absent. Set to absent to detach all entities from this policy and remove it if found.
59 default: present
60 choices: [ "present", "absent" ]
61 type: str
62 notes:
63 - Support for O(tags) and O(purge_tags) was added in release 7.2.0.
64
65 author:
66 - "Dan Kozlowski (@dkhenry)"
67 extends_documentation_fragment:
68 - amazon.aws.common.modules
69 - amazon.aws.region.modules
70 - amazon.aws.tags.modules
71 - amazon.aws.boto3
72 """
73
74 EXAMPLES = r"""
75 # Create a policy
76 - name: Create IAM Managed Policy
77 amazon.aws.iam_managed_policy:
78 policy_name: "ManagedPolicy"
79 policy_description: "A Helpful managed policy"
80 policy: "{{ lookup('template', 'managed_policy.json.j2') }}"
81 state: present
82
83 # Update a policy with a new default version
84 - name: Update an IAM Managed Policy with new default version
85 amazon.aws.iam_managed_policy:
86 policy_name: "ManagedPolicy"
87 policy: "{{ lookup('file', 'managed_policy_update.json') }}"
88 state: present
89
90 # Update a policy with a new non default version
91 - name: Update an IAM Managed Policy with a non default version
92 amazon.aws.iam_managed_policy:
93 policy_name: "ManagedPolicy"
94 policy:
95 Version: "2012-10-17"
96 Statement:
97 - Effect: "Allow"
98 Action: "logs:CreateLogGroup"
99 Resource: "*"
100 make_default: false
101 state: present
102
103 # Update a policy and make it the only version and the default version
104 - name: Update an IAM Managed Policy with default version as the only version
105 amazon.aws.iam_managed_policy:
106 policy_name: "ManagedPolicy"
107 policy: |
108 {
109 "Version": "2012-10-17",
110 "Statement":[{
111 "Effect": "Allow",
112 "Action": "logs:PutRetentionPolicy",
113 "Resource": "*"
114 }]
115 }
116 only_version: true
117 state: present
118
119 # Remove a policy
120 - name: Remove an existing IAM Managed Policy
121 amazon.aws.iam_managed_policy:
122 policy_name: "ManagedPolicy"
123 state: absent
124 """
125
126 RETURN = r"""
127 policy:
128 description: Returns the basic policy information, when O(state=absent) this will return the value of the removed policy.
129 returned: always
130 type: complex
131 contains:
132 arn:
133 description: The Amazon Resource Name (ARN) of the policy.
134 type: str
135 returned: success
136 sample: "arn:aws:iam::123456789012:policy/ansible-test-12345/ansible-test-12345-policy"
137 attachment_count:
138 description: The number of entities (users, groups, and roles) that the policy is attached to.
139 type: int
140 returned: success
141 sample: 5
142 create_date:
143 description: The date and time, in ISO 8601 date-time format, when the policy was created.
144 type: str
145 returned: success
146 sample: "2017-02-08T04:36:28+00:00"
147 default_version_id:
148 description: The default policy version to use.
149 type: str
150 returned: success
151 sample: "/ansible-test-12345/"
152 description:
153 description: A friendly description of the policy.
154 type: str
155 returned: success
156 sample: "My Example Policy"
157 is_attachable:
158 description: Specifies whether the policy can be attached to an IAM entities.
159 type: bool
160 returned: success
161 sample: False
162 path:
163 description: The path to the policy.
164 type: str
165 returned: success
166 sample: "/ansible-test-12345/"
167 permissions_boundary_usage_count:
168 description: The number of IAM entities (users, groups, and roles) using the policy as a permissions boundary.
169 type: int
170 returned: success
171 sample: 5
172 policy_id:
173 description: The stable and globally unique string identifying the policy.
174 type: str
175 returned: success
176 sample: "ANPA12345EXAMPLE12345"
177 policy_name:
178 description: The friendly name identifying the policy.
179 type: str
180 returned: success
181 sample: "ansible-test-12345-policy"
182 tags:
183 description: A dictionary representing the tags attached to the managed policy.
184 type: dict
185 returned: success
186 sample: {"Env": "Prod"}
187 update_date:
188 description: The date and time, in ISO 8601 date-time format, when the policy was last updated.
189 type: str
190 returned: success
191 sample: "2017-02-08T05:12:13+00:00"
192 """
193
194 import json
195
196 from ansible.module_utils.common.text.converters import to_native
197
198 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
199 from ansible_collections.amazon.aws.plugins.module_utils.iam import AnsibleIAMError
200 from ansible_collections.amazon.aws.plugins.module_utils.iam import IAMErrorHandler
201 from ansible_collections.amazon.aws.plugins.module_utils.iam import detach_iam_group_policy
202 from ansible_collections.amazon.aws.plugins.module_utils.iam import detach_iam_role_policy
203 from ansible_collections.amazon.aws.plugins.module_utils.iam import detach_iam_user_policy
204 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_iam_managed_policy_by_arn
205 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_iam_managed_policy_by_name
206 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_iam_managed_policy_version
207 from ansible_collections.amazon.aws.plugins.module_utils.iam import list_iam_entities_for_policy
208 from ansible_collections.amazon.aws.plugins.module_utils.iam import list_iam_managed_policy_versions
209 from ansible_collections.amazon.aws.plugins.module_utils.iam import normalize_iam_policy
210 from ansible_collections.amazon.aws.plugins.module_utils.iam import tag_iam_policy
211 from ansible_collections.amazon.aws.plugins.module_utils.iam import untag_iam_policy
212 from ansible_collections.amazon.aws.plugins.module_utils.iam import validate_iam_identifiers
213 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
214 from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies
215 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
216 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
217 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
218 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
219
220
221 @IAMErrorHandler.deletion_error_handler("delete policy version")
222 def delete_policy_version(arn, version):
223 client.delete_policy_version(aws_retry=True, PolicyArn=arn, VersionId=version)
224
225
226 def _create_policy_version(arn, policy_document):
227 return client.create_policy_version(aws_retry=True, PolicyArn=arn, PolicyDocument=policy_document)["PolicyVersion"]
228
229
230 @IAMErrorHandler.common_error_handler("create policy version")
231 def create_policy_version(arn, policy_document):
232 if module.check_mode:
233 return {}
234 try:
235 version = _create_policy_version(arn, policy_document)
236 # There is a service limit (typically 5) of policy versions.
237 #
238 # Rather than assume that it is 5, we'll try to create the policy
239 # and if that doesn't work, delete the oldest non default policy version
240 # and try again.
241 except is_boto3_error_code("LimitExceeded"):
242 delete_oldest_non_default_version(arn)
243 version = _create_policy_version(arn, policy_document)
244
245 return version
246
247
248 def delete_oldest_non_default_version(arn):
249 if module.check_mode:
250 return True
251
252 versions = [v for v in list_iam_managed_policy_versions(client, arn) if not v["IsDefaultVersion"]]
253 if not versions:
254 return False
255
256 versions.sort(key=lambda v: v["CreateDate"], reverse=True)
257 for v in versions[-1:]:
258 delete_policy_version(arn, v["VersionId"])
259 return True
260
261
262 # This needs to return policy_version, changed
263 def get_or_create_policy_version(policy, policy_document):
264 versions = list_iam_managed_policy_versions(client, policy["Arn"])
265
266 for v in versions:
267 document = get_iam_managed_policy_version(client, policy["Arn"], v["VersionId"])["Document"]
268
269 # If the current policy matches the existing one
270 if not compare_policies(document, json.loads(to_native(policy_document))):
271 return v, False
272
273 # No existing version so create one
274 return create_policy_version(policy["Arn"], policy_document), True
275
276
277 @IAMErrorHandler.common_error_handler("set default policy version")
278 def set_if_default(policy, policy_version, is_default):
279 if not is_default:
280 return False
281 if policy_version.get("IsDefaultVersion"):
282 return False
283 if module.check_mode:
284 return True
285
286 client.set_default_policy_version(aws_retry=True, PolicyArn=policy["Arn"], VersionId=policy_version["VersionId"])
287 return True
288
289
290 def set_if_only(policy, policy_version, is_only):
291 if not is_only:
292 return False
293 versions = [v for v in list_iam_managed_policy_versions(client, policy["Arn"]) if not v["IsDefaultVersion"]]
294 if not versions:
295 return False
296 if module.check_mode:
297 return True
298
299 for v in versions:
300 delete_policy_version(policy["Arn"], v["VersionId"])
301
302 return True
303
304
305 def detach_all_entities(policy):
306 arn = policy["Arn"]
307 entities = list_iam_entities_for_policy(client, arn)
308
309 if not entities:
310 return False
311
312 for g in entities["PolicyGroups"]:
313 detach_iam_group_policy(client, arn, g["GroupName"])
314 for u in entities["PolicyUsers"]:
315 detach_iam_user_policy(client, arn, u["UserName"])
316 for r in entities["PolicyRoles"]:
317 detach_iam_role_policy(client, arn, r["RoleName"])
318
319 return True
320
321
322 @IAMErrorHandler.common_error_handler("create policy")
323 def create_managed_policy(name, path, policy, description, tags):
324 if module.check_mode:
325 module.exit_json(changed=True)
326 if policy is None:
327 raise AnsibleIAMError(message="Managed policy would be created but policy parameter is missing")
328
329 params = {"PolicyName": name, "PolicyDocument": policy}
330
331 if path:
332 params["Path"] = path
333 if description:
334 params["Description"] = description
335 if tags:
336 params["Tags"] = ansible_dict_to_boto3_tag_list(tags)
337
338 rvalue = client.create_policy(aws_retry=True, **params)
339 # rvalue is incomplete
340 new_policy = get_iam_managed_policy_by_arn(client, rvalue["Policy"]["Arn"])
341
342 module.exit_json(changed=True, policy=normalize_iam_policy(new_policy))
343
344
345 def ensure_path(existing_policy, path):
346 if path is None:
347 return False
348
349 existing_path = existing_policy["Path"]
350 if existing_path == path:
351 return False
352
353 # As of botocore 1.34.3, the APIs don't support updating the Name or Path
354 module.warn(f"Unable to update path from '{existing_path}' to '{path}'")
355 return False
356
357
358 def ensure_description(existing_policy, description):
359 if description is None:
360 return False
361
362 existing_description = existing_policy.get("Description", "")
363 if existing_description == description:
364 return False
365
366 # As of botocore 1.34.3, the APIs don't support updating the Description
367 module.warn(f"Unable to update description from '{existing_description}' to '{description}'")
368 return False
369
370
371 def ensure_policy_document(existing_policy, policy, default, only):
372 if policy is None:
373 return False
374 policy_version, changed = get_or_create_policy_version(existing_policy, policy)
375 changed |= set_if_default(existing_policy, policy_version, default)
376 changed |= set_if_only(existing_policy, policy_version, only)
377 return changed
378
379
380 def ensure_tags(existing_policy, tags, purge_tags):
381 if tags is None:
382 return False
383
384 original_tags = boto3_tag_list_to_ansible_dict(existing_policy.get("Tags") or [])
385
386 tags_to_set, tag_keys_to_unset = compare_aws_tags(original_tags, tags, purge_tags)
387 if not tags_to_set and not tag_keys_to_unset:
388 return False
389
390 if module.check_mode:
391 return True
392
393 if tag_keys_to_unset:
394 untag_iam_policy(client, existing_policy["Arn"], tag_keys_to_unset)
395 if tags_to_set:
396 tag_iam_policy(client, existing_policy["Arn"], tags_to_set)
397
398 return True
399
400
401 def update_managed_policy(existing_policy, path, policy, description, default, only, tags, purge_tags):
402 changed = ensure_path(existing_policy, path)
403 changed |= ensure_description(existing_policy, description)
404 changed |= ensure_policy_document(existing_policy, policy, default, only)
405 changed |= ensure_tags(existing_policy, tags, purge_tags)
406
407 if not changed:
408 module.exit_json(changed=changed, policy=normalize_iam_policy(existing_policy))
409
410 # If anything has changed we need to refresh the policy
411 updated_policy = get_iam_managed_policy_by_arn(client, existing_policy["Arn"])
412 module.exit_json(changed=changed, policy=normalize_iam_policy(updated_policy))
413
414
415 def create_or_update_policy(existing_policy):
416 name = module.params.get("name")
417 path = module.params.get("path")
418 description = module.params.get("description")
419 default = module.params.get("make_default")
420 only = module.params.get("only_version")
421 tags = module.params.get("tags")
422 purge_tags = module.params.get("purge_tags")
423
424 policy = None
425
426 if module.params.get("policy") is not None:
427 policy = json.dumps(json.loads(module.params.get("policy")))
428
429 if existing_policy is None:
430 create_managed_policy(name, path, policy, description, tags)
431 else:
432 update_managed_policy(existing_policy, path, policy, description, default, only, tags, purge_tags)
433
434
435 @IAMErrorHandler.deletion_error_handler("delete policy")
436 def delete_policy(existing_policy):
437 if not existing_policy:
438 return False
439
440 arn = existing_policy["Arn"]
441 if module.check_mode:
442 return True
443
444 # Detach policy
445 detach_all_entities(existing_policy)
446 # Delete Versions
447 versions = [v for v in list_iam_managed_policy_versions(client, arn) if not v["IsDefaultVersion"]]
448 for v in versions:
449 delete_policy_version(arn, v["VersionId"])
450
451 # Delete policy
452 client.delete_policy(aws_retry=True, PolicyArn=arn)
453 return True
454
455
456 def main():
457 global module
458 global client
459
460 argument_spec = dict(
461 name=dict(required=True, aliases=["policy_name"]),
462 path=dict(aliases=["prefix", "path_prefix"]),
463 description=dict(aliases=["policy_description"]),
464 policy=dict(type="json"),
465 make_default=dict(type="bool", default=True),
466 only_version=dict(type="bool", default=False),
467 state=dict(default="present", choices=["present", "absent"]),
468 tags=dict(type="dict", aliases=["resource_tags"]),
469 purge_tags=dict(type="bool", default=True),
470 )
471
472 module = AnsibleAWSModule(
473 argument_spec=argument_spec,
474 supports_check_mode=True,
475 )
476
477 name = module.params.get("name")
478 state = module.params.get("state")
479
480 identifier_problem = validate_iam_identifiers("policy", name=name)
481 if identifier_problem:
482 module.fail_json(msg=identifier_problem)
483
484 client = module.client("iam", retry_decorator=AWSRetry.jittered_backoff())
485
486 existing_policy = get_iam_managed_policy_by_name(client, name)
487
488 try:
489 if state == "present":
490 create_or_update_policy(existing_policy)
491 else:
492 changed = delete_policy(existing_policy)
493 module.exit_json(changed=changed, policy=normalize_iam_policy(existing_policy))
494 except AnsibleIAMError as e:
495 module.fail_json_aws_error(e)
496
497
498 if __name__ == "__main__":
499 main()