Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/iam_instance_profile.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_instance_profile
10 version_added: 6.2.0
11 short_description: manage IAM instance profiles
12 description:
13 - Manage IAM instance profiles.
14 author:
15 - Mark Chappell (@tremble)
16 options:
17 state:
18 description:
19 - Desired state of the instance profile.
20 type: str
21 choices: ["absent", "present"]
22 default: "present"
23 name:
24 description:
25 - Name of the instance profile.
26 - >-
27 Note: Profile names are unique within an account. Paths (O(path)) do B(not) affect
28 the uniqueness requirements of O(name). For example it is not permitted to have both
29 C(/Path1/MyProfile) and C(/Path2/MyProfile) in the same account.
30 aliases: ["instance_profile_name"]
31 type: str
32 required: True
33 path:
34 description:
35 - The instance profile path.
36 - For more information about IAM paths, see the AWS IAM identifiers documentation
37 U(https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html).
38 - Updating the path on an existing profile is not currently supported and will result in a
39 warning.
40 - The parameter was renamed from O(prefix) to O(path) in release 7.2.0.
41 aliases: ["path_prefix", "prefix"]
42 type: str
43 role:
44 description:
45 - The name of the role to attach to the instance profile.
46 - To remove all roles from the instance profile set O(role="").
47 type: str
48
49 extends_documentation_fragment:
50 - amazon.aws.common.modules
51 - amazon.aws.region.modules
52 - amazon.aws.tags.modules
53 - amazon.aws.boto3
54 """
55
56 EXAMPLES = r"""
57 - name: Create Instance Profile
58 amazon.aws.iam_instance_profile:
59 name: "ExampleInstanceProfile"
60 role: "/OurExamples/MyExampleRole"
61 path: "/OurExamples/"
62 tags:
63 ExampleTag: Example Value
64 register: profile_result
65
66 - name: Create second Instance Profile with default path
67 amazon.aws.iam_instance_profile:
68 name: "ExampleInstanceProfile2"
69 role: "/OurExamples/MyExampleRole"
70 tags:
71 ExampleTag: Another Example Value
72 register: profile_result
73
74 - name: Find all IAM instance profiles starting with /OurExamples/
75 amazon.aws.iam_instance_profile_info:
76 path_prefix: /OurExamples/
77 register: result
78
79 - name: Delete second Instance Profile
80 amazon.aws.iam_instance_profile:
81 name: "ExampleInstanceProfile2"
82 state: absent
83 """
84
85 RETURN = r"""
86 iam_instance_profile:
87 description: List of IAM instance profiles.
88 returned: always
89 type: complex
90 contains:
91 arn:
92 description: Amazon Resource Name for the instance profile.
93 returned: always
94 type: str
95 sample: arn:aws:iam::123456789012:instance-profile/AnsibleTestProfile
96 create_date:
97 description: Date instance profile was created.
98 returned: always
99 type: str
100 sample: '2023-01-12T11:18:29+00:00'
101 instance_profile_id:
102 description: Amazon Identifier for the instance profile.
103 returned: always
104 type: str
105 sample: AROA12345EXAMPLE54321
106 instance_profile_name:
107 description: Name of instance profile.
108 returned: always
109 type: str
110 sample: AnsibleTestEC2Policy
111 path:
112 description: Path of instance profile.
113 returned: always
114 type: str
115 sample: /
116 roles:
117 description: List of roles associated with this instance profile.
118 returned: always
119 type: list
120 sample: []
121 tags:
122 description: Instance profile tags.
123 type: dict
124 returned: always
125 sample: '{"Env": "Prod"}'
126 """
127
128 from copy import deepcopy
129
130 from ansible_collections.amazon.aws.plugins.module_utils.iam import AnsibleIAMError
131 from ansible_collections.amazon.aws.plugins.module_utils.iam import add_role_to_iam_instance_profile
132 from ansible_collections.amazon.aws.plugins.module_utils.iam import create_iam_instance_profile
133 from ansible_collections.amazon.aws.plugins.module_utils.iam import delete_iam_instance_profile
134 from ansible_collections.amazon.aws.plugins.module_utils.iam import list_iam_instance_profiles
135 from ansible_collections.amazon.aws.plugins.module_utils.iam import normalize_iam_instance_profile
136 from ansible_collections.amazon.aws.plugins.module_utils.iam import remove_role_from_iam_instance_profile
137 from ansible_collections.amazon.aws.plugins.module_utils.iam import tag_iam_instance_profile
138 from ansible_collections.amazon.aws.plugins.module_utils.iam import untag_iam_instance_profile
139 from ansible_collections.amazon.aws.plugins.module_utils.iam import validate_iam_identifiers
140 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
141 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
142 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
143
144
145 def describe_iam_instance_profile(client, name, prefix):
146 profiles = []
147 profiles = list_iam_instance_profiles(client, name=name, prefix=prefix)
148
149 if not profiles:
150 return None
151
152 return normalize_iam_instance_profile(profiles[0])
153
154
155 def create_instance_profile(client, name, path, tags, check_mode):
156 if check_mode:
157 return True, {"instance_profile_name": name, "path": path, "tags": tags or {}, "roles": []}
158
159 profile = create_iam_instance_profile(client, name, path, tags)
160 return True, normalize_iam_instance_profile(profile)
161
162
163 def ensure_tags(
164 original_profile,
165 client,
166 name,
167 tags,
168 purge_tags,
169 check_mode,
170 ):
171 if tags is None:
172 return False, original_profile
173
174 original_tags = original_profile.get("tags") or {}
175
176 tags_to_set, tag_keys_to_unset = compare_aws_tags(original_tags, tags, purge_tags)
177 if not tags_to_set and not tag_keys_to_unset:
178 return False, original_profile
179
180 new_profile = deepcopy(original_profile)
181 desired_tags = deepcopy(original_tags)
182
183 for key in tag_keys_to_unset:
184 desired_tags.pop(key, None)
185 desired_tags.update(tags_to_set)
186 new_profile["tags"] = desired_tags
187
188 if not check_mode:
189 untag_iam_instance_profile(client, name, tag_keys_to_unset)
190 tag_iam_instance_profile(client, name, tags_to_set)
191
192 return True, new_profile
193
194
195 def ensure_role(
196 original_profile,
197 client,
198 name,
199 role,
200 check_mode,
201 ):
202 if role is None:
203 return False, original_profile
204
205 if role == "" and not original_profile.get("roles"):
206 return False, original_profile
207 else:
208 desired_role = []
209
210 if original_profile.get("roles") and original_profile.get("roles")[0].get("role_name", None) == role:
211 return False, original_profile
212 else:
213 desired_role = [{"role_name": role}]
214
215 new_profile = deepcopy(original_profile)
216 new_profile["roles"] = desired_role
217
218 if check_mode:
219 return True, new_profile
220
221 if original_profile.get("roles"):
222 # We're changing the role, so we always need to remove the existing one first
223 remove_role_from_iam_instance_profile(client, name, original_profile["roles"][0]["role_name"])
224 if role:
225 add_role_to_iam_instance_profile(client, name, role)
226
227 return True, new_profile
228
229
230 def ensure_present(
231 original_profile,
232 client,
233 name,
234 path,
235 tags,
236 purge_tags,
237 role,
238 check_mode,
239 ):
240 changed = False
241 if not original_profile:
242 changed, new_profile = create_instance_profile(
243 client,
244 name=name,
245 path=path,
246 tags=tags,
247 check_mode=check_mode,
248 )
249 else:
250 new_profile = deepcopy(original_profile)
251
252 role_changed, new_profile = ensure_role(
253 new_profile,
254 client,
255 name,
256 role,
257 check_mode,
258 )
259
260 tags_changed, new_profile = ensure_tags(
261 new_profile,
262 client,
263 name,
264 tags,
265 purge_tags,
266 check_mode,
267 )
268
269 changed |= role_changed
270 changed |= tags_changed
271
272 return changed, new_profile
273
274
275 def ensure_absent(
276 original_profile,
277 client,
278 name,
279 prefix,
280 check_mode,
281 ):
282 if not original_profile:
283 return False
284
285 if check_mode:
286 return True
287
288 roles = original_profile.get("roles") or []
289 for role in roles:
290 remove_role_from_iam_instance_profile(client, name, role.get("role_name"))
291
292 return delete_iam_instance_profile(client, name)
293
294
295 def main():
296 """
297 Module action handler
298 """
299 argument_spec = dict(
300 name=dict(aliases=["instance_profile_name"], required=True),
301 path=dict(aliases=["path_prefix", "prefix"]),
302 state=dict(choices=["absent", "present"], default="present"),
303 tags=dict(aliases=["resource_tags"], type="dict"),
304 purge_tags=dict(type="bool", default=True),
305 role=dict(),
306 )
307
308 module = AnsibleAWSModule(
309 argument_spec=argument_spec,
310 supports_check_mode=True,
311 )
312
313 name = module.params.get("name")
314 state = module.params.get("state")
315 path = module.params.get("path")
316
317 identifier_problem = validate_iam_identifiers("instance profile", name=name, path=path)
318 if identifier_problem:
319 module.fail_json(msg=identifier_problem)
320
321 client = module.client("iam", retry_decorator=AWSRetry.jittered_backoff())
322 try:
323 original_profile = describe_iam_instance_profile(client, name, path)
324
325 if state == "absent":
326 changed = ensure_absent(
327 original_profile,
328 client,
329 name,
330 path,
331 module.check_mode,
332 )
333 final_profile = None
334 else:
335 # As of botocore 1.34.3, the APIs don't support updating the Name or Path
336 if original_profile and path and original_profile.get("path") != path:
337 module.warn(
338 "iam_instance_profile doesn't support updating the path: "
339 f"current path '{original_profile.get('path')}', requested path '{path}'"
340 )
341
342 changed, final_profile = ensure_present(
343 original_profile,
344 client,
345 name,
346 path,
347 module.params["tags"],
348 module.params["purge_tags"],
349 module.params["role"],
350 module.check_mode,
351 )
352
353 if not module.check_mode:
354 final_profile = describe_iam_instance_profile(client, name, path)
355
356 except AnsibleIAMError as e:
357 module.fail_json_aws_error(e)
358
359 results = {
360 "changed": changed,
361 "iam_instance_profile": final_profile,
362 }
363 if changed:
364 results["diff"] = {
365 "before": original_profile,
366 "after": final_profile,
367 }
368 module.exit_json(**results)
369
370
371 if __name__ == "__main__":
372 main()