Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/iam_group.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the 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_group
10 version_added: 1.0.0
11 version_added_collection: community.aws
12 short_description: Manage AWS IAM groups
13 description:
14 - Manage AWS IAM groups.
15 author:
16 - Nick Aslanidis (@naslanidis)
17 - Maksym Postument (@infectsoldier)
18 options:
19 name:
20 description:
21 - The name of the group.
22 - >-
23 Note: Group names are unique within an account. Paths (O(path)) do B(not) affect
24 the uniqueness requirements of O(name). For example it is not permitted to have both
25 C(/Path1/MyGroup) and C(/Path2/MyGroup) in the same account.
26 - The alias O(group_name) was added in release 7.2.0.
27 required: true
28 aliases: ['group_name']
29 type: str
30 path:
31 description:
32 - The group path.
33 - For more information about IAM paths, see the AWS IAM identifiers documentation
34 U(https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html).
35 aliases: ['prefix', 'path_prefix']
36 version_added: 7.1.0
37 type: str
38 managed_policies:
39 description:
40 - A list of managed policy ARNs or friendly names to attach to the role.
41 - If known, it is recommended to use ARNs rather than friendly names to avoid additional
42 lookups.
43 - To embed an inline policy, use M(amazon.aws.iam_policy).
44 required: false
45 type: list
46 elements: str
47 default: []
48 aliases: ['managed_policy']
49 users:
50 description:
51 - A list of existing users to add as members of the group.
52 required: false
53 type: list
54 elements: str
55 default: []
56 state:
57 description:
58 - Create or remove the IAM group.
59 required: true
60 choices: [ 'present', 'absent' ]
61 type: str
62 purge_policies:
63 description:
64 - When O(purge_policies=true) any managed policies not listed in O(managed_policies) will be detatched.
65 required: false
66 default: false
67 type: bool
68 aliases: ['purge_policy', 'purge_managed_policies']
69 purge_users:
70 description:
71 - When O(purge_users=true) users which are not included in I(users) will be detached.
72 required: false
73 default: false
74 type: bool
75 extends_documentation_fragment:
76 - amazon.aws.common.modules
77 - amazon.aws.region.modules
78 - amazon.aws.boto3
79 """
80
81 EXAMPLES = r"""
82 # Note: These examples do not set authentication details, see the AWS Guide for details.
83
84 - name: Create a group
85 amazon.aws.iam_group:
86 name: testgroup1
87 state: present
88
89 - name: Create a group and attach a managed policy using its ARN
90 amazon.aws.iam_group:
91 name: testgroup1
92 managed_policies:
93 - arn:aws:iam::aws:policy/AmazonSNSFullAccess
94 state: present
95
96 - name: Create a group with users as members and attach a managed policy using its ARN
97 amazon.aws.iam_group:
98 name: testgroup1
99 managed_policies:
100 - arn:aws:iam::aws:policy/AmazonSNSFullAccess
101 users:
102 - test_user1
103 - test_user2
104 state: present
105
106 - name: Remove all managed policies from an existing group with an empty list
107 amazon.aws.iam_group:
108 name: testgroup1
109 state: present
110 purge_policies: true
111
112 - name: Remove all group members from an existing group
113 amazon.aws.iam_group:
114 name: testgroup1
115 managed_policies:
116 - arn:aws:iam::aws:policy/AmazonSNSFullAccess
117 purge_users: true
118 state: present
119
120 - name: Delete the group
121 amazon.aws.iam_group:
122 name: testgroup1
123 state: absent
124 """
125
126 RETURN = r"""
127 iam_group:
128 description: Dictionary containing all the group information including group membership.
129 returned: success
130 type: complex
131 contains:
132 group:
133 description: Dictionary containing all the group information.
134 returned: success
135 type: complex
136 contains:
137 arn:
138 description: The Amazon Resource Name (ARN) specifying the group.
139 type: str
140 sample: "arn:aws:iam::1234567890:group/testgroup1"
141 create_date:
142 description: The date and time, in ISO 8601 date-time format, when the group was created.
143 type: str
144 sample: "2017-02-08T04:36:28+00:00"
145 group_id:
146 description: The stable and unique string identifying the group.
147 type: str
148 sample: AGPA12345EXAMPLE54321
149 group_name:
150 description: The friendly name that identifies the group.
151 type: str
152 sample: testgroup1
153 path:
154 description: The path to the group.
155 type: str
156 sample: /
157 users:
158 description: List containing all the group members.
159 returned: success
160 type: complex
161 contains:
162 arn:
163 description: The Amazon Resource Name (ARN) specifying the user.
164 type: str
165 sample: "arn:aws:iam::1234567890:user/test_user1"
166 create_date:
167 description: The date and time, in ISO 8601 date-time format, when the user was created.
168 type: str
169 sample: "2017-02-08T04:36:28+00:00"
170 user_id:
171 description: The stable and unique string identifying the user.
172 type: str
173 sample: AIDA12345EXAMPLE54321
174 user_name:
175 description: The friendly name that identifies the user.
176 type: str
177 sample: testgroup1
178 path:
179 description: The path to the user.
180 type: str
181 sample: /
182 attached_policies:
183 version_added: 7.1.0
184 description:
185 - List containing basic information about managed policies attached to the group.
186 returned: success
187 type: complex
188 contains:
189 policy_arn:
190 description: The Amazon Resource Name (ARN) specifying the managed policy.
191 type: str
192 sample: "arn:aws:iam::123456789012:policy/test_policy"
193 policy_name:
194 description: The friendly name that identifies the policy.
195 type: str
196 sample: test_policy
197 """
198
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 convert_managed_policy_names_to_arns
202 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_iam_group
203 from ansible_collections.amazon.aws.plugins.module_utils.iam import normalize_iam_group
204 from ansible_collections.amazon.aws.plugins.module_utils.iam import validate_iam_identifiers
205 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
206 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
207
208
209 @IAMErrorHandler.common_error_handler("update group path")
210 def ensure_path(connection, module, group_info, path):
211 if path is None:
212 return False
213
214 if group_info["Group"].get("Path") == path:
215 return False
216
217 if module.check_mode:
218 return True
219
220 connection.update_group(
221 aws_retry=True,
222 GroupName=group_info["Group"]["GroupName"],
223 NewPath=path,
224 )
225 return True
226
227
228 def detach_policies(connection, module, group_name, policies):
229 for policy_arn in policies:
230 IAMErrorHandler.deletion_error_handler(f"detach policy {policy_arn} from group")(
231 connection.detach_group_policy
232 )(aws_retry=True, GroupName=group_name, PolicyArn=policy_arn)
233
234
235 def attach_policies(connection, module, group_name, policies):
236 for policy_arn in policies:
237 IAMErrorHandler.common_error_handler(f"attach policy {policy_arn} to group")(connection.attach_group_policy)(
238 aws_retry=True, GroupName=group_name, PolicyArn=policy_arn
239 )
240
241
242 def ensure_managed_policies(connection, module, group_info, managed_policies, purge_policies):
243 if managed_policies is None:
244 return False
245
246 if managed_policies:
247 managed_policies = convert_managed_policy_names_to_arns(connection, managed_policies)
248
249 group_name = group_info["Group"]["GroupName"]
250
251 current_attached_policies_desc = get_attached_policy_list(connection, module, group_name)
252 current_attached_policies = [policy["PolicyArn"] for policy in current_attached_policies_desc]
253
254 policies_to_add = list(set(managed_policies) - set(current_attached_policies))
255 policies_to_remove = []
256 if purge_policies:
257 policies_to_remove = list(set(current_attached_policies) - set(managed_policies))
258
259 if not policies_to_add and not policies_to_remove:
260 return False
261
262 if module.check_mode:
263 return True
264
265 detach_policies(connection, module, group_name, policies_to_remove)
266 attach_policies(connection, module, group_name, policies_to_add)
267
268 return True
269
270
271 def add_group_members(connection, module, group_name, members):
272 for user in members:
273 IAMErrorHandler.common_error_handler(f"add user {user} to group")(connection.add_user_to_group)(
274 aws_retry=True, GroupName=group_name, UserName=user
275 )
276
277
278 def remove_group_members(connection, module, group_name, members):
279 for user in members:
280 IAMErrorHandler.deletion_error_handler(f"remove user {user} from group")(connection.remove_user_from_group)(
281 aws_retry=True, GroupName=group_name, UserName=user
282 )
283
284
285 def ensure_group_members(connection, module, group_info, users, purge_users):
286 if users is None:
287 return False
288
289 group_name = group_info["Group"]["GroupName"]
290 current_group_members = [member["UserName"] for member in group_info["Users"]]
291
292 members_to_add = list(set(users) - set(current_group_members))
293 members_to_remove = []
294 if purge_users:
295 members_to_remove = list(set(current_group_members) - set(users))
296
297 if not members_to_add and not members_to_remove:
298 return False
299
300 if module.check_mode:
301 return True
302
303 add_group_members(connection, module, group_name, members_to_add)
304 remove_group_members(connection, module, group_name, members_to_remove)
305
306 return True
307
308
309 @IAMErrorHandler.common_error_handler("create group")
310 def get_or_create_group(connection, module, group_name, path):
311 group = get_iam_group(connection, group_name)
312 if group:
313 return False, group
314
315 params = {"GroupName": group_name}
316 if path is not None:
317 params["Path"] = path
318
319 # Check mode means we would create the group
320 if module.check_mode:
321 module.exit_json(changed=True, create_params=params)
322
323 group = connection.create_group(aws_retry=True, **params)
324
325 if "Users" not in group:
326 group["Users"] = []
327
328 return True, group
329
330
331 def create_or_update_group(connection, module):
332 changed, group_info = get_or_create_group(connection, module, module.params["name"], module.params["path"])
333
334 # Update the path if necessary
335 changed |= ensure_path(
336 connection,
337 module,
338 group_info,
339 module.params["path"],
340 )
341
342 # Manage managed policies
343 changed |= ensure_managed_policies(
344 connection,
345 module,
346 group_info,
347 module.params["managed_policies"],
348 module.params["purge_policies"],
349 )
350
351 # Manage group memberships
352 changed |= ensure_group_members(
353 connection,
354 module,
355 group_info,
356 module.params["users"],
357 module.params["purge_users"],
358 )
359
360 if module.check_mode:
361 module.exit_json(changed=changed)
362
363 # Get the group again
364 group_info = get_iam_group(connection, module.params["name"])
365 policies = get_attached_policy_list(connection, module, module.params["name"])
366 group_info["AttachedPolicies"] = policies
367
368 module.exit_json(changed=changed, iam_group=normalize_iam_group(group_info))
369
370
371 @IAMErrorHandler.deletion_error_handler("delete group")
372 def destroy_group(connection, module):
373 group_name = module.params.get("name")
374
375 group = get_iam_group(connection, group_name)
376
377 if not group:
378 module.exit_json(changed=False)
379
380 # Check mode means we would remove this group
381 if module.check_mode:
382 module.exit_json(changed=True)
383
384 # Remove any attached policies otherwise deletion fails
385 current_policies_desc = get_attached_policy_list(connection, module, group_name)
386 current_policies = [policy["PolicyArn"] for policy in current_policies_desc]
387 detach_policies(connection, module, group_name, current_policies)
388
389 # Remove any users in the group otherwise deletion fails
390 current_group_members = [user["UserName"] for user in group["Users"]]
391 remove_group_members(connection, module, group_name, current_group_members)
392
393 connection.delete_group(aws_retry=True, GroupName=group_name)
394
395 module.exit_json(changed=True)
396
397
398 @IAMErrorHandler.list_error_handler("list policies attached to group")
399 @AWSRetry.jittered_backoff()
400 def get_attached_policy_list(connection, module, name):
401 paginator = connection.get_paginator("list_attached_group_policies")
402 return paginator.paginate(GroupName=name).build_full_result()["AttachedPolicies"]
403
404
405 def main():
406 argument_spec = dict(
407 name=dict(aliases=["group_name"], required=True),
408 path=dict(aliases=["prefix", "path_prefix"]),
409 managed_policies=dict(default=[], type="list", aliases=["managed_policy"], elements="str"),
410 users=dict(default=[], type="list", elements="str"),
411 state=dict(choices=["present", "absent"], required=True),
412 purge_users=dict(default=False, type="bool"),
413 purge_policies=dict(default=False, type="bool", aliases=["purge_policy", "purge_managed_policies"]),
414 )
415
416 module = AnsibleAWSModule(
417 argument_spec=argument_spec,
418 supports_check_mode=True,
419 )
420
421 identifier_problem = validate_iam_identifiers(
422 "group", name=module.params.get("name"), path=module.params.get("path")
423 )
424 if identifier_problem:
425 module.fail_json(msg=identifier_problem)
426
427 connection = module.client("iam", retry_decorator=AWSRetry.jittered_backoff())
428
429 state = module.params.get("state")
430
431 try:
432 if state == "present":
433 create_or_update_group(connection, module)
434 else:
435 destroy_group(connection, module)
436 except AnsibleIAMError as e:
437 module.fail_json_aws_error(e)
438
439
440 if __name__ == "__main__":
441 main()