Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 Jon Meran <[email protected]>
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: batch_job_definition
10 version_added: 1.0.0
11 short_description: Manage AWS Batch Job Definitions
12 description:
13 - This module allows the management of AWS Batch Job Definitions.
14 - It is idempotent and supports "Check" mode.
15 - Use module M(community.aws.batch_compute_environment) to manage the compute
16 environment, M(community.aws.batch_job_queue) to manage job queues, M(community.aws.batch_job_definition) to manage job definitions.
17 - Prior to release 5.0.0 this module was called C(community.aws.aws_batch_job_definition).
18 The usage did not change.
19 author:
20 - Jon Meran (@jonmer85)
21 options:
22 job_definition_arn:
23 description:
24 - The ARN for the job definition.
25 type: str
26 job_definition_name:
27 description:
28 - The name for the job definition.
29 required: true
30 type: str
31 state:
32 description:
33 - Describes the desired state.
34 default: "present"
35 choices: ["present", "absent"]
36 type: str
37 type:
38 description:
39 - The type of job definition.
40 required: true
41 type: str
42 parameters:
43 description:
44 - Default parameter substitution placeholders to set in the job definition. Parameters are specified as a
45 key-value pair mapping. Parameters in a SubmitJob request override any corresponding parameter defaults from
46 the job definition.
47 type: dict
48 image:
49 description:
50 - >
51 The image used to start a container. This string is passed directly to the Docker daemon. Images in the Docker
52 Hub registry are available by default. Other repositories are specified with C(repository-url/image-name:tag).
53 Up to 255 letters (uppercase and lowercase), numbers, hyphens, underscores, colons, periods, forward slashes,
54 and number signs are allowed. This parameter maps to Image in the Create a container section of the Docker
55 Remote API and the IMAGE parameter of docker run.
56 required: true
57 type: str
58 vcpus:
59 description:
60 - The number of vCPUs reserved for the container. This parameter maps to CpuShares in the Create a container
61 section of the Docker Remote API and the --cpu-shares option to docker run. Each vCPU is equivalent to
62 1,024 CPU shares.
63 required: true
64 type: int
65 memory:
66 description:
67 - The hard limit (in MiB) of memory to present to the container. If your container attempts to exceed the memory
68 specified here, the container is killed. This parameter maps to Memory in the Create a container section of the
69 Docker Remote API and the --memory option to docker run.
70 required: true
71 type: int
72 command:
73 description:
74 - The command that is passed to the container. This parameter maps to Cmd in the Create a container section of
75 the Docker Remote API and the COMMAND parameter to docker run. For more information,
76 see U(https://docs.docker.com/engine/reference/builder/#cmd).
77 type: list
78 elements: str
79 default: []
80 job_role_arn:
81 description:
82 - The Amazon Resource Name (ARN) of the IAM role that the container can assume for AWS permissions.
83 type: str
84 volumes:
85 description:
86 - A list of data volumes used in a job.
87 suboptions:
88 host:
89 description:
90 - The contents of the host parameter determine whether your data volume persists on the host container
91 instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns a host
92 path for your data volume, but the data is not guaranteed to persist after the containers associated with
93 it stop running.
94 This is a dictionary with one property, sourcePath - The path on the host container
95 instance that is presented to the container. If this parameter is empty,then the Docker daemon has assigned
96 a host path for you. If the host parameter contains a sourcePath file location, then the data volume
97 persists at the specified location on the host container instance until you delete it manually. If the
98 sourcePath value does not exist on the host container instance, the Docker daemon creates it. If the
99 location does exist, the contents of the source path folder are exported.
100 name:
101 description:
102 - The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are
103 allowed. This name is referenced in the sourceVolume parameter of container definition mountPoints.
104 type: list
105 elements: dict
106 default: []
107 environment:
108 description:
109 - The environment variables to pass to a container. This parameter maps to Env in the Create a container section
110 of the Docker Remote API and the --env option to docker run.
111 suboptions:
112 name:
113 description:
114 - The name of the key value pair. For environment variables, this is the name of the environment variable.
115 value:
116 description:
117 - The value of the key value pair. For environment variables, this is the value of the environment variable.
118 type: list
119 elements: dict
120 default: []
121 mount_points:
122 description:
123 - The mount points for data volumes in your container. This parameter maps to Volumes in the Create a container
124 section of the Docker Remote API and the --volume option to docker run.
125 suboptions:
126 containerPath:
127 description:
128 - The path on the container at which to mount the host volume.
129 readOnly:
130 description:
131 - If this value is true , the container has read-only access to the volume; otherwise, the container can write
132 to the volume. The default value is C(false).
133 sourceVolume:
134 description:
135 - The name of the volume to mount.
136 type: list
137 elements: dict
138 default: []
139 readonly_root_filesystem:
140 description:
141 - When this parameter is true, the container is given read-only access to its root file system. This parameter
142 maps to ReadonlyRootfs in the Create a container section of the Docker Remote API and the --read-only option
143 to docker run.
144 type: str
145 privileged:
146 description:
147 - When this parameter is true, the container is given elevated privileges on the host container instance
148 (similar to the root user). This parameter maps to Privileged in the Create a container section of the
149 Docker Remote API and the --privileged option to docker run.
150 type: str
151 ulimits:
152 description:
153 - A list of ulimits to set in the container. This parameter maps to Ulimits in the Create a container section
154 of the Docker Remote API and the --ulimit option to docker run.
155 suboptions:
156 hardLimit:
157 description:
158 - The hard limit for the ulimit type.
159 name:
160 description:
161 - The type of the ulimit.
162 softLimit:
163 description:
164 - The soft limit for the ulimit type.
165 type: list
166 elements: dict
167 default: []
168 user:
169 description:
170 - The user name to use inside the container. This parameter maps to User in the Create a container section of
171 the Docker Remote API and the --user option to docker run.
172 type: str
173 attempts:
174 description:
175 - Retry strategy - The number of times to move a job to the RUNNABLE status. You may specify between 1 and 10
176 attempts. If attempts is greater than one, the job is retried if it fails until it has moved to RUNNABLE that
177 many times.
178 type: int
179 extends_documentation_fragment:
180 - amazon.aws.common.modules
181 - amazon.aws.region.modules
182 - amazon.aws.boto3
183 """
184
185 EXAMPLES = r"""
186 ---
187 - name: My Batch Job Definition
188 community.aws.batch_job_definition:
189 job_definition_name: My Batch Job Definition
190 state: present
191 type: container
192 parameters:
193 Param1: Val1
194 Param2: Val2
195 image: <Docker Image URL>
196 vcpus: 1
197 memory: 512
198 command:
199 - python
200 - run_my_script.py
201 - arg1
202 job_role_arn: <Job Role ARN>
203 attempts: 3
204 register: job_definition_create_result
205
206 - name: show results
207 ansible.builtin.debug: var=job_definition_create_result
208 """
209
210 RETURN = r"""
211 ---
212 output:
213 description: "returns what action was taken, whether something was changed, invocation and response"
214 returned: always
215 sample:
216 aws_batch_job_definition_action: none
217 changed: false
218 response:
219 job_definition_arn: "arn:aws:batch:...."
220 job_definition_name: <name>
221 status: INACTIVE
222 type: container
223 type: dict
224 """
225
226 try:
227 from botocore.exceptions import BotoCoreError
228 from botocore.exceptions import ClientError
229 except ImportError:
230 pass # Handled by AnsibleAWSModule
231
232 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
233
234 from ansible_collections.amazon.aws.plugins.module_utils.batch import cc
235 from ansible_collections.amazon.aws.plugins.module_utils.batch import set_api_params
236
237 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
238
239 # ---------------------------------------------------------------------------------------------------
240 #
241 # Helper Functions & classes
242 #
243 # ---------------------------------------------------------------------------------------------------
244
245 # logger = logging.getLogger()
246 # logging.basicConfig(filename='ansible_debug.log')
247 # logger.setLevel(logging.DEBUG)
248
249
250 def validate_params(module, batch_client):
251 """
252 Performs basic parameter validation.
253
254 :param module:
255 :param batch_client:
256 :return:
257 """
258 return
259
260
261 # ---------------------------------------------------------------------------------------------------
262 #
263 # Batch Job Definition functions
264 #
265 # ---------------------------------------------------------------------------------------------------
266
267
268 def get_current_job_definition(module, batch_client):
269 try:
270 environments = batch_client.describe_job_definitions(jobDefinitionName=module.params["job_definition_name"])
271 if len(environments["jobDefinitions"]) > 0:
272 latest_revision = max(map(lambda d: d["revision"], environments["jobDefinitions"]))
273 latest_definition = next(
274 (x for x in environments["jobDefinitions"] if x["revision"] == latest_revision), None
275 )
276 return latest_definition
277 return None
278 except ClientError:
279 return None
280
281
282 def create_job_definition(module, batch_client):
283 """
284 Adds a Batch job definition
285
286 :param module:
287 :param batch_client:
288 :return:
289 """
290
291 changed = False
292
293 # set API parameters
294 api_params = set_api_params(module, get_base_params())
295 container_properties_params = set_api_params(module, get_container_property_params())
296 retry_strategy_params = set_api_params(module, get_retry_strategy_params())
297
298 api_params["retryStrategy"] = retry_strategy_params
299 api_params["containerProperties"] = container_properties_params
300
301 try:
302 if not module.check_mode:
303 batch_client.register_job_definition(**api_params)
304 changed = True
305 except (BotoCoreError, ClientError) as e:
306 module.fail_json_aws(e, msg="Error registering job definition")
307
308 return changed
309
310
311 def get_retry_strategy_params():
312 return ("attempts",)
313
314
315 def get_container_property_params():
316 return (
317 "image",
318 "vcpus",
319 "memory",
320 "command",
321 "job_role_arn",
322 "volumes",
323 "environment",
324 "mount_points",
325 "readonly_root_filesystem",
326 "privileged",
327 "ulimits",
328 "user",
329 )
330
331
332 def get_base_params():
333 return "job_definition_name", "type", "parameters"
334
335
336 def get_compute_environment_order_list(module):
337 compute_environment_order_list = []
338 for ceo in module.params["compute_environment_order"]:
339 compute_environment_order_list.append(dict(order=ceo["order"], computeEnvironment=ceo["compute_environment"]))
340 return compute_environment_order_list
341
342
343 def remove_job_definition(module, batch_client):
344 """
345 Remove a Batch job definition
346
347 :param module:
348 :param batch_client:
349 :return:
350 """
351
352 changed = False
353
354 try:
355 if not module.check_mode:
356 batch_client.deregister_job_definition(jobDefinition=module.params["job_definition_arn"])
357 changed = True
358 except (BotoCoreError, ClientError) as e:
359 module.fail_json_aws(e, msg="Error removing job definition")
360 return changed
361
362
363 def job_definition_equal(module, current_definition):
364 equal = True
365
366 for param in get_base_params():
367 if module.params.get(param) != current_definition.get(cc(param)):
368 equal = False
369 break
370
371 for param in get_container_property_params():
372 if module.params.get(param) != current_definition.get("containerProperties").get(cc(param)):
373 equal = False
374 break
375
376 for param in get_retry_strategy_params():
377 if module.params.get(param) != current_definition.get("retryStrategy").get(cc(param)):
378 equal = False
379 break
380
381 return equal
382
383
384 def manage_state(module, batch_client):
385 changed = False
386 current_state = "absent"
387 state = module.params["state"]
388 action_taken = "none"
389 response = None
390
391 # check if the job definition exists
392 current_job_definition = get_current_job_definition(module, batch_client)
393 if current_job_definition:
394 current_state = "present"
395
396 if state == "present":
397 if current_state == "present":
398 # check if definition has changed and register a new version if necessary
399 if not job_definition_equal(module, current_job_definition):
400 create_job_definition(module, batch_client)
401 action_taken = "updated with new version"
402 changed = True
403 else:
404 # Create Job definition
405 changed = create_job_definition(module, batch_client)
406 action_taken = "added"
407
408 response = get_current_job_definition(module, batch_client)
409 if not response:
410 module.fail_json(msg="Unable to get job definition information after creating/updating")
411 else:
412 if current_state == "present":
413 # remove the Job definition
414 changed = remove_job_definition(module, batch_client)
415 action_taken = "deregistered"
416 return dict(changed=changed, batch_job_definition_action=action_taken, response=response)
417
418
419 # ---------------------------------------------------------------------------------------------------
420 #
421 # MAIN
422 #
423 # ---------------------------------------------------------------------------------------------------
424
425
426 def main():
427 """
428 Main entry point.
429
430 :return dict: ansible facts
431 """
432
433 argument_spec = dict(
434 state=dict(required=False, default="present", choices=["present", "absent"]),
435 job_definition_name=dict(required=True),
436 job_definition_arn=dict(),
437 type=dict(required=True),
438 parameters=dict(type="dict"),
439 image=dict(required=True),
440 vcpus=dict(type="int", required=True),
441 memory=dict(type="int", required=True),
442 command=dict(type="list", default=[], elements="str"),
443 job_role_arn=dict(),
444 volumes=dict(type="list", default=[], elements="dict"),
445 environment=dict(type="list", default=[], elements="dict"),
446 mount_points=dict(type="list", default=[], elements="dict"),
447 readonly_root_filesystem=dict(),
448 privileged=dict(),
449 ulimits=dict(type="list", default=[], elements="dict"),
450 user=dict(),
451 attempts=dict(type="int"),
452 )
453
454 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
455
456 batch_client = module.client("batch")
457
458 validate_params(module, batch_client)
459
460 results = manage_state(module, batch_client)
461
462 module.exit_json(**camel_dict_to_snake_dict(results))
463
464
465 if __name__ == "__main__":
466 main()