Debian Codegraph @

ansible_collections/community/aws/plugins/modules/glue_job.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Rob White (@wimnat)
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: glue_job
10 version_added: 1.0.0
11 short_description: Manage an AWS Glue job
12 description:
13 - Manage an AWS Glue job. See U(https://aws.amazon.com/glue/) for details.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_glue_job).
15 The usage did not change.
16 author:
17 - "Rob White (@wimnat)"
18 - "Vijayanand Sharma (@vijayanandsharma)"
19 options:
20 allocated_capacity:
21 description:
22 - The number of AWS Glue data processing units (DPUs) to allocate to this Job. From 2 to 100 DPUs
23 can be allocated; the default is 10. A DPU is a relative measure of processing power that consists
24 of 4 vCPUs of compute capacity and 16 GB of memory.
25 type: int
26 command_name:
27 description:
28 - The name of the job command. This must be 'glueetl'.
29 default: glueetl
30 type: str
31 command_python_version:
32 description:
33 - Python version being used to execute a Python shell job.
34 - AWS currently supports C('2') or C('3').
35 type: str
36 version_added: 2.2.0
37 command_script_location:
38 description:
39 - The S3 path to a script that executes a job.
40 - Required when I(state=present).
41 type: str
42 connections:
43 description:
44 - A list of Glue connections used for this job.
45 type: list
46 elements: str
47 default_arguments:
48 description:
49 - A dict of default arguments for this job. You can specify arguments here that your own job-execution
50 script consumes, as well as arguments that AWS Glue itself consumes.
51 type: dict
52 description:
53 description:
54 - Description of the job being defined.
55 type: str
56 glue_version:
57 description:
58 - Glue version determines the versions of Apache Spark and Python that AWS Glue supports.
59 type: str
60 version_added: 1.5.0
61 max_concurrent_runs:
62 description:
63 - The maximum number of concurrent runs allowed for the job. The default is 1. An error is returned when
64 this threshold is reached. The maximum value you can specify is controlled by a service limit.
65 type: int
66 max_retries:
67 description:
68 - The maximum number of times to retry this job if it fails.
69 type: int
70 name:
71 description:
72 - The name you assign to this job definition. It must be unique in your account.
73 required: true
74 type: str
75 number_of_workers:
76 description:
77 - The number of workers of a defined workerType that are allocated when a job runs.
78 type: int
79 version_added: 1.5.0
80 role:
81 description:
82 - The name or ARN of the IAM role associated with this job.
83 - Required when I(state=present).
84 type: str
85 state:
86 description:
87 - Create or delete the AWS Glue job.
88 required: true
89 choices: [ 'present', 'absent' ]
90 type: str
91 timeout:
92 description:
93 - The job timeout in minutes.
94 type: int
95 worker_type:
96 description:
97 - The type of predefined worker that is allocated when a job runs.
98 - Support for instance types C(G.4X( and C(G.8X) was added in community.aws release 7.2.0.
99 choices: [ 'Standard', 'G.1X', 'G.2X', 'G.4X', 'G.8X' ]
100 type: str
101 version_added: 1.5.0
102 notes:
103 - Support for I(tags) and I(purge_tags) was added in release 2.2.0.
104 extends_documentation_fragment:
105 - amazon.aws.common.modules
106 - amazon.aws.region.modules
107 - amazon.aws.tags
108 - amazon.aws.boto3
109 """
110
111 EXAMPLES = r"""
112 # Note: These examples do not set authentication details, see the AWS Guide for details.
113
114 # Create an AWS Glue job
115 - community.aws.glue_job:
116 command_script_location: "s3://s3bucket/script.py"
117 default_arguments:
118 "--extra-py-files": s3://s3bucket/script-package.zip
119 "--TempDir": "s3://s3bucket/temp/"
120 name: my-glue-job
121 role: my-iam-role
122 state: present
123
124 # Delete an AWS Glue job
125 - community.aws.glue_job:
126 name: my-glue-job
127 state: absent
128 """
129
130 RETURN = r"""
131 allocated_capacity:
132 description: The number of AWS Glue data processing units (DPUs) allocated to runs of this job. From 2 to
133 100 DPUs can be allocated; the default is 10. A DPU is a relative measure of processing power
134 that consists of 4 vCPUs of compute capacity and 16 GB of memory.
135 returned: when state is present
136 type: int
137 sample: 10
138 command:
139 description: The JobCommand that executes this job.
140 returned: when state is present
141 type: complex
142 contains:
143 name:
144 description: The name of the job command.
145 returned: when state is present
146 type: str
147 sample: glueetl
148 script_location:
149 description: Specifies the S3 path to a script that executes a job.
150 returned: when state is present
151 type: str
152 sample: mybucket/myscript.py
153 python_version:
154 description: Specifies the Python version.
155 returned: when state is present
156 type: str
157 sample: 3
158 connections:
159 description: The connections used for this job.
160 returned: when state is present
161 type: dict
162 sample: "{ Connections: [ 'list', 'of', 'connections' ] }"
163 created_on:
164 description: The time and date that this job definition was created.
165 returned: when state is present
166 type: str
167 sample: "2018-04-21T05:19:58.326000+00:00"
168 default_arguments:
169 description: The default arguments for this job, specified as name-value pairs.
170 returned: when state is present
171 type: dict
172 sample: "{ 'mykey1': 'myvalue1' }"
173 description:
174 description: Description of the job being defined.
175 returned: when state is present
176 type: str
177 sample: My first Glue job
178 glue_version:
179 description: Glue version.
180 returned: when state is present
181 type: str
182 sample: 2.0
183 job_name:
184 description: The name of the AWS Glue job.
185 returned: always
186 type: str
187 sample: my-glue-job
188 execution_property:
189 description: An ExecutionProperty specifying the maximum number of concurrent runs allowed for this job.
190 returned: always
191 type: complex
192 contains:
193 max_concurrent_runs:
194 description: The maximum number of concurrent runs allowed for the job. The default is 1. An error is
195 returned when this threshold is reached. The maximum value you can specify is controlled by
196 a service limit.
197 returned: when state is present
198 type: int
199 sample: 1
200 last_modified_on:
201 description: The last point in time when this job definition was modified.
202 returned: when state is present
203 type: str
204 sample: "2018-04-21T05:19:58.326000+00:00"
205 max_retries:
206 description: The maximum number of times to retry this job after a JobRun fails.
207 returned: when state is present
208 type: int
209 sample: 5
210 name:
211 description: The name assigned to this job definition.
212 returned: when state is present
213 type: str
214 sample: my-glue-job
215 role:
216 description: The name or ARN of the IAM role associated with this job.
217 returned: when state is present
218 type: str
219 sample: my-iam-role
220 timeout:
221 description: The job timeout in minutes.
222 returned: when state is present
223 type: int
224 sample: 300
225 """
226
227 import copy
228
229 try:
230 import botocore
231 except ImportError:
232 pass # Handled by AnsibleAWSModule
233
234 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
235
236 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
237 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_aws_account_info
238 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
239 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
240
241 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
242
243
244 def _get_glue_job(connection, module, glue_job_name):
245 """
246 Get an AWS Glue job based on name. If not found, return None.
247
248 :param connection: AWS boto3 glue connection
249 :param module: Ansible module
250 :param glue_job_name: Name of Glue job to get
251 :return: boto3 Glue job dict or None if not found
252 """
253 try:
254 return connection.get_job(aws_retry=True, JobName=glue_job_name)["Job"]
255 except is_boto3_error_code("EntityNotFoundException"):
256 return None
257 except (
258 botocore.exceptions.ClientError,
259 botocore.exceptions.BotoCoreError,
260 ) as e: # pylint: disable=duplicate-except
261 module.fail_json_aws(e)
262
263
264 def _compare_glue_job_params(user_params, current_params):
265 """
266 Compare Glue job params. If there is a difference, return True immediately else return False
267
268 :param user_params: the Glue job parameters passed by the user
269 :param current_params: the Glue job parameters currently configured
270 :return: True if any parameter is mismatched else False
271 """
272 # Weirdly, boto3 doesn't return some keys if the value is empty e.g. Description
273 # To counter this, add the key if it's missing with a blank value
274
275 if "Description" not in current_params:
276 current_params["Description"] = ""
277 if "DefaultArguments" not in current_params:
278 current_params["DefaultArguments"] = dict()
279
280 if "AllocatedCapacity" in user_params and user_params["AllocatedCapacity"] != current_params["AllocatedCapacity"]:
281 return True
282 if "Command" in user_params:
283 if user_params["Command"]["ScriptLocation"] != current_params["Command"]["ScriptLocation"]:
284 return True
285 if user_params["Command"]["PythonVersion"] != current_params["Command"]["PythonVersion"]:
286 return True
287 if "Connections" in user_params and user_params["Connections"] != current_params["Connections"]:
288 return True
289 if "DefaultArguments" in user_params and user_params["DefaultArguments"] != current_params["DefaultArguments"]:
290 return True
291 if "Description" in user_params and user_params["Description"] != current_params["Description"]:
292 return True
293 if (
294 "ExecutionProperty" in user_params
295 and user_params["ExecutionProperty"]["MaxConcurrentRuns"]
296 != current_params["ExecutionProperty"]["MaxConcurrentRuns"]
297 ):
298 return True
299 if "GlueVersion" in user_params and user_params["GlueVersion"] != current_params["GlueVersion"]:
300 return True
301 if "MaxRetries" in user_params and user_params["MaxRetries"] != current_params["MaxRetries"]:
302 return True
303 if "Role" in user_params and user_params["Role"] != current_params["Role"]:
304 return True
305 if "Timeout" in user_params and user_params["Timeout"] != current_params["Timeout"]:
306 return True
307 if "GlueVersion" in user_params and user_params["GlueVersion"] != current_params["GlueVersion"]:
308 return True
309 if "WorkerType" in user_params and user_params["WorkerType"] != current_params["WorkerType"]:
310 return True
311 if "NumberOfWorkers" in user_params and user_params["NumberOfWorkers"] != current_params["NumberOfWorkers"]:
312 return True
313
314 return False
315
316
317 def ensure_tags(connection, module, glue_job):
318 changed = False
319
320 if module.params.get("tags") is None:
321 return False
322
323 account_id, partition = get_aws_account_info(module)
324 arn = f"arn:{partition}:glue:{module.region}:{account_id}:job/{module.params.get('name')}"
325
326 try:
327 existing_tags = connection.get_tags(aws_retry=True, ResourceArn=arn).get("Tags", {})
328 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
329 if module.check_mode:
330 existing_tags = {}
331 else:
332 module.fail_json_aws(e, msg=f"Unable to get tags for Glue job {module.params.get('name')}")
333
334 tags_to_add, tags_to_remove = compare_aws_tags(
335 existing_tags, module.params.get("tags"), module.params.get("purge_tags")
336 )
337
338 if tags_to_remove:
339 changed = True
340 if not module.check_mode:
341 try:
342 connection.untag_resource(aws_retry=True, ResourceArn=arn, TagsToRemove=tags_to_remove)
343 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
344 module.fail_json_aws(e, msg=f"Unable to set tags for Glue job {module.params.get('name')}")
345
346 if tags_to_add:
347 changed = True
348 if not module.check_mode:
349 try:
350 connection.tag_resource(aws_retry=True, ResourceArn=arn, TagsToAdd=tags_to_add)
351 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
352 module.fail_json_aws(e, msg=f"Unable to set tags for Glue job {module.params.get('name')}")
353
354 return changed
355
356
357 def create_or_update_glue_job(connection, module, glue_job):
358 """
359 Create or update an AWS Glue job
360
361 :param connection: AWS boto3 glue connection
362 :param module: Ansible module
363 :param glue_job: a dict of AWS Glue job parameters or None
364 :return:
365 """
366
367 changed = False
368 params = dict()
369 params["Name"] = module.params.get("name")
370 params["Role"] = module.params.get("role")
371 if module.params.get("allocated_capacity") is not None:
372 params["AllocatedCapacity"] = module.params.get("allocated_capacity")
373 if module.params.get("command_script_location") is not None:
374 params["Command"] = {
375 "Name": module.params.get("command_name"),
376 "ScriptLocation": module.params.get("command_script_location"),
377 }
378 if module.params.get("command_python_version") is not None:
379 params["Command"]["PythonVersion"] = module.params.get("command_python_version")
380 if module.params.get("connections") is not None:
381 params["Connections"] = {"Connections": module.params.get("connections")}
382 if module.params.get("default_arguments") is not None:
383 params["DefaultArguments"] = module.params.get("default_arguments")
384 if module.params.get("description") is not None:
385 params["Description"] = module.params.get("description")
386 if module.params.get("glue_version") is not None:
387 params["GlueVersion"] = module.params.get("glue_version")
388 if module.params.get("max_concurrent_runs") is not None:
389 params["ExecutionProperty"] = {"MaxConcurrentRuns": module.params.get("max_concurrent_runs")}
390 if module.params.get("max_retries") is not None:
391 params["MaxRetries"] = module.params.get("max_retries")
392 if module.params.get("timeout") is not None:
393 params["Timeout"] = module.params.get("timeout")
394 if module.params.get("glue_version") is not None:
395 params["GlueVersion"] = module.params.get("glue_version")
396 if module.params.get("worker_type") is not None:
397 params["WorkerType"] = module.params.get("worker_type")
398 if module.params.get("number_of_workers") is not None:
399 params["NumberOfWorkers"] = module.params.get("number_of_workers")
400
401 # If glue_job is not None then check if it needs to be modified, else create it
402 if glue_job:
403 if _compare_glue_job_params(params, glue_job):
404 try:
405 # Update job needs slightly modified params
406 update_params = {"JobName": params["Name"], "JobUpdate": copy.deepcopy(params)}
407 del update_params["JobUpdate"]["Name"]
408 if not module.check_mode:
409 connection.update_job(aws_retry=True, **update_params)
410 changed = True
411 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
412 module.fail_json_aws(e)
413 else:
414 try:
415 if not module.check_mode:
416 connection.create_job(aws_retry=True, **params)
417 changed = True
418 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
419 module.fail_json_aws(e)
420
421 glue_job = _get_glue_job(connection, module, params["Name"])
422
423 changed |= ensure_tags(connection, module, glue_job)
424
425 module.exit_json(changed=changed, **camel_dict_to_snake_dict(glue_job or {}, ignore_list=["DefaultArguments"]))
426
427
428 def delete_glue_job(connection, module, glue_job):
429 """
430 Delete an AWS Glue job
431
432 :param connection: AWS boto3 glue connection
433 :param module: Ansible module
434 :param glue_job: a dict of AWS Glue job parameters or None
435 :return:
436 """
437 changed = False
438
439 if glue_job:
440 try:
441 if not module.check_mode:
442 connection.delete_job(aws_retry=True, JobName=glue_job["Name"])
443 changed = True
444 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
445 module.fail_json_aws(e)
446
447 module.exit_json(changed=changed)
448
449
450 def main():
451 argument_spec = dict(
452 allocated_capacity=dict(type="int"),
453 command_name=dict(type="str", default="glueetl"),
454 command_python_version=dict(type="str"),
455 command_script_location=dict(type="str"),
456 connections=dict(type="list", elements="str"),
457 default_arguments=dict(type="dict"),
458 description=dict(type="str"),
459 glue_version=dict(type="str"),
460 max_concurrent_runs=dict(type="int"),
461 max_retries=dict(type="int"),
462 name=dict(required=True, type="str"),
463 number_of_workers=dict(type="int"),
464 purge_tags=dict(type="bool", default=True),
465 role=dict(type="str"),
466 state=dict(required=True, choices=["present", "absent"], type="str"),
467 tags=dict(type="dict", aliases=["resource_tags"]),
468 timeout=dict(type="int"),
469 worker_type=dict(choices=["Standard", "G.1X", "G.2X", "G.4X", "G.8X"], type="str"),
470 )
471
472 module = AnsibleAWSModule(
473 argument_spec=argument_spec,
474 required_if=[("state", "present", ["role", "command_script_location"])],
475 supports_check_mode=True,
476 )
477
478 retry_decorator = AWSRetry.jittered_backoff(retries=10)
479 connection = module.client("glue", retry_decorator=retry_decorator)
480
481 state = module.params.get("state")
482
483 glue_job = _get_glue_job(connection, module, module.params.get("name"))
484
485 if state == "present":
486 create_or_update_glue_job(connection, module, glue_job)
487 else:
488 delete_glue_job(connection, module, glue_job)
489
490
491 if __name__ == "__main__":
492 main()