Debian Codegraph @

ansible_collections/community/aws/plugins/modules/batch_compute_environment.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_compute_environment
10 version_added: 1.0.0
11 short_description: Manage AWS Batch Compute Environments
12 description:
13 - This module allows the management of AWS Batch Compute Environments.
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_compute_environment).
18 The usage did not change.
19 author:
20 - Jon Meran (@jonmer85)
21 options:
22 compute_environment_name:
23 description:
24 - The name for your compute environment.
25 - Up to 128 letters (uppercase and lowercase), numbers, and underscores are allowed.
26 required: true
27 type: str
28 type:
29 description:
30 - The type of the compute environment.
31 required: true
32 choices: ["MANAGED", "UNMANAGED"]
33 type: str
34 state:
35 description:
36 - Describes the desired state.
37 default: "present"
38 choices: ["present", "absent"]
39 type: str
40 compute_environment_state:
41 description:
42 - The state of the compute environment.
43 - If the state is C(ENABLED), then the compute environment accepts jobs
44 from a queue and can scale out automatically based on queues.
45 default: "ENABLED"
46 choices: ["ENABLED", "DISABLED"]
47 type: str
48 service_role:
49 description:
50 - The full Amazon Resource Name (ARN) of the IAM role that allows AWS Batch to make calls to other AWS
51 services on your behalf.
52 required: true
53 type: str
54 compute_resource_type:
55 description:
56 - The type of compute resource.
57 required: true
58 choices: ["EC2", "SPOT"]
59 type: str
60 minv_cpus:
61 description:
62 - The minimum number of EC2 vCPUs that an environment should maintain.
63 required: true
64 type: int
65 maxv_cpus:
66 description:
67 - The maximum number of EC2 vCPUs that an environment can reach.
68 required: true
69 type: int
70 desiredv_cpus:
71 description:
72 - The desired number of EC2 vCPUS in the compute environment.
73 type: int
74 instance_types:
75 description:
76 - The instance types that may be launched.
77 required: true
78 type: list
79 elements: str
80 image_id:
81 description:
82 - The Amazon Machine Image (AMI) ID used for instances launched in the compute environment.
83 type: str
84 subnets:
85 description:
86 - The VPC subnets into which the compute resources are launched.
87 required: true
88 type: list
89 elements: str
90 security_group_ids:
91 description:
92 - The EC2 security groups that are associated with instances launched in the compute environment.
93 required: true
94 type: list
95 elements: str
96 ec2_key_pair:
97 description:
98 - The EC2 key pair that is used for instances launched in the compute environment.
99 type: str
100 instance_role:
101 description:
102 - The Amazon ECS instance role applied to Amazon EC2 instances in a compute environment.
103 required: true
104 type: str
105 tags:
106 description:
107 - Key-value pair tags to be applied to resources that are launched in the compute environment.
108 type: dict
109 bid_percentage:
110 description:
111 - The minimum percentage that a Spot Instance price must be when compared with the On-Demand price for that
112 instance type before instances are launched.
113 - For example, if your bid percentage is 20%, then the Spot price
114 must be below 20% of the current On-Demand price for that EC2 instance.
115 type: int
116 spot_iam_fleet_role:
117 description:
118 - The Amazon Resource Name (ARN) of the Amazon EC2 Spot Fleet IAM role applied to a SPOT compute environment.
119 type: str
120 extends_documentation_fragment:
121 - amazon.aws.common.modules
122 - amazon.aws.region.modules
123 - amazon.aws.boto3
124 """
125
126 EXAMPLES = r"""
127 - name: My Batch Compute Environment
128 community.aws.batch_compute_environment:
129 compute_environment_name: computeEnvironmentName
130 state: present
131 region: us-east-1
132 compute_environment_state: ENABLED
133 type: MANAGED
134 compute_resource_type: EC2
135 minv_cpus: 0
136 maxv_cpus: 2
137 desiredv_cpus: 1
138 instance_types:
139 - optimal
140 subnets:
141 - my-subnet1
142 - my-subnet2
143 security_group_ids:
144 - my-sg1
145 - my-sg2
146 instance_role: arn:aws:iam::<account>:instance-profile/<role>
147 tags:
148 tag1: value1
149 tag2: value2
150 service_role: arn:aws:iam::<account>:role/service-role/<role>
151 register: aws_batch_compute_environment_action
152
153 - name: show results
154 ansible.builtin.debug:
155 var: aws_batch_compute_environment_action
156 """
157
158 RETURN = r"""
159 ---
160 output:
161 description: "returns what action was taken, whether something was changed, invocation and response"
162 returned: always
163 sample:
164 batch_compute_environment_action: none
165 changed: false
166 invocation:
167 module_args:
168 access_key: ~
169 secret_key: ~
170 bid_percentage: ~
171 compute_environment_name: <name>
172 compute_environment_state: ENABLED
173 compute_resource_type: EC2
174 desiredv_cpus: 0
175 ec2_key_pair: ~
176 endpoint_url: ~
177 image_id: ~
178 instance_role: "arn:aws:iam::..."
179 instance_types:
180 - optimal
181 maxv_cpus: 8
182 minv_cpus: 0
183 profile: ~
184 region: us-east-1
185 security_group_ids:
186 - "*******"
187 security_token: ~
188 service_role: "arn:aws:iam::...."
189 spot_iam_fleet_role: ~
190 state: present
191 subnets:
192 - "******"
193 tags:
194 Environment: <name>
195 Name: <name>
196 type: MANAGED
197 validate_certs: true
198 response:
199 computeEnvironmentArn: "arn:aws:batch:...."
200 computeEnvironmentName: <name>
201 computeResources:
202 desiredvCpus: 0
203 instanceRole: "arn:aws:iam::..."
204 instanceTypes:
205 - optimal
206 maxvCpus: 8
207 minvCpus: 0
208 securityGroupIds:
209 - "******"
210 subnets:
211 - "*******"
212 tags:
213 Environment: <name>
214 Name: <name>
215 type: EC2
216 ecsClusterArn: "arn:aws:ecs:....."
217 serviceRole: "arn:aws:iam::..."
218 state: ENABLED
219 status: VALID
220 statusReason: "ComputeEnvironment Healthy"
221 type: MANAGED
222 type: dict
223 """
224
225 import re
226
227 try:
228 from botocore.exceptions import BotoCoreError
229 from botocore.exceptions import ClientError
230 except ImportError:
231 pass # Handled by AnsibleAWSModule
232
233 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
234 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
235
236 from ansible_collections.amazon.aws.plugins.module_utils.arn import validate_aws_arn
237
238 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
239
240 # ---------------------------------------------------------------------------------------------------
241 #
242 # Helper Functions & classes
243 #
244 # ---------------------------------------------------------------------------------------------------
245
246
247 def set_api_params(module, module_params):
248 """
249 Sets module parameters to those expected by the boto3 API.
250
251 :param module:
252 :param module_params:
253 :return:
254 """
255 api_params = dict((k, v) for k, v in dict(module.params).items() if k in module_params and v is not None)
256 return snake_dict_to_camel_dict(api_params)
257
258
259 def validate_params(module):
260 """
261 Performs basic parameter validation.
262
263 :param module:
264 :return:
265 """
266
267 compute_environment_name = module.params["compute_environment_name"]
268
269 # validate compute environment name
270 if not re.search(r"^[\w\_:]+$", compute_environment_name):
271 module.fail_json(
272 msg=f"Function compute_environment_name {compute_environment_name} is invalid. Names must contain only alphanumeric characters and underscores."
273 )
274 if not validate_aws_arn(compute_environment_name, service="batch"):
275 if len(compute_environment_name) > 128:
276 module.fail_json(msg=f'compute_environment_name "{compute_environment_name}" exceeds 128 character limit')
277
278 return
279
280
281 # ---------------------------------------------------------------------------------------------------
282 #
283 # Batch Compute Environment functions
284 #
285 # ---------------------------------------------------------------------------------------------------
286
287
288 def get_current_compute_environment(module, client):
289 try:
290 environments = client.describe_compute_environments(
291 computeEnvironments=[module.params["compute_environment_name"]]
292 )
293 if len(environments["computeEnvironments"]) > 0:
294 return environments["computeEnvironments"][0]
295 else:
296 return None
297 except ClientError:
298 return None
299
300
301 def create_compute_environment(module, client):
302 """
303 Adds a Batch compute environment
304
305 :param module:
306 :param client:
307 :return:
308 """
309
310 changed = False
311
312 # set API parameters
313 params = ("compute_environment_name", "type", "service_role")
314 api_params = set_api_params(module, params)
315
316 if module.params["compute_environment_state"] is not None:
317 api_params["state"] = module.params["compute_environment_state"]
318
319 compute_resources_param_list = (
320 "minv_cpus",
321 "maxv_cpus",
322 "desiredv_cpus",
323 "instance_types",
324 "image_id",
325 "subnets",
326 "security_group_ids",
327 "ec2_key_pair",
328 "instance_role",
329 "tags",
330 "bid_percentage",
331 "spot_iam_fleet_role",
332 )
333 compute_resources_params = set_api_params(module, compute_resources_param_list)
334
335 if module.params["compute_resource_type"] is not None:
336 compute_resources_params["type"] = module.params["compute_resource_type"]
337
338 # if module.params['minv_cpus'] is not None:
339 # compute_resources_params['minvCpus'] = module.params['minv_cpus']
340
341 api_params["computeResources"] = compute_resources_params
342
343 try:
344 if not module.check_mode:
345 client.create_compute_environment(**api_params)
346 changed = True
347 except (ClientError, BotoCoreError) as e:
348 module.fail_json_aws(e, msg="Error creating compute environment")
349
350 return changed
351
352
353 def remove_compute_environment(module, client):
354 """
355 Remove a Batch compute environment
356
357 :param module:
358 :param client:
359 :return:
360 """
361
362 changed = False
363
364 # set API parameters
365 api_params = {"computeEnvironment": module.params["compute_environment_name"]}
366
367 try:
368 if not module.check_mode:
369 client.delete_compute_environment(**api_params)
370 changed = True
371 except (ClientError, BotoCoreError) as e:
372 module.fail_json_aws(e, msg="Error removing compute environment")
373 return changed
374
375
376 def manage_state(module, client):
377 changed = False
378 current_state = "absent"
379 state = module.params["state"]
380 compute_environment_state = module.params["compute_environment_state"]
381 compute_environment_name = module.params["compute_environment_name"]
382 service_role = module.params["service_role"]
383 minv_cpus = module.params["minv_cpus"]
384 maxv_cpus = module.params["maxv_cpus"]
385 desiredv_cpus = module.params["desiredv_cpus"]
386 action_taken = "none"
387 update_env_response = ""
388
389 check_mode = module.check_mode
390
391 # check if the compute environment exists
392 current_compute_environment = get_current_compute_environment(module, client)
393 response = current_compute_environment
394 if current_compute_environment:
395 current_state = "present"
396
397 if state == "present":
398 if current_state == "present":
399 updates = False
400 # Update Batch Compute Environment configuration
401 compute_kwargs = {"computeEnvironment": compute_environment_name}
402
403 # Update configuration if needed
404 compute_resources = {}
405 if compute_environment_state and current_compute_environment["state"] != compute_environment_state:
406 compute_kwargs.update({"state": compute_environment_state})
407 updates = True
408 if service_role and current_compute_environment["serviceRole"] != service_role:
409 compute_kwargs.update({"serviceRole": service_role})
410 updates = True
411 if minv_cpus is not None and current_compute_environment["computeResources"]["minvCpus"] != minv_cpus:
412 compute_resources["minvCpus"] = minv_cpus
413 if maxv_cpus is not None and current_compute_environment["computeResources"]["maxvCpus"] != maxv_cpus:
414 compute_resources["maxvCpus"] = maxv_cpus
415 if (
416 desiredv_cpus is not None
417 and current_compute_environment["computeResources"]["desiredvCpus"] != desiredv_cpus
418 ):
419 compute_resources["desiredvCpus"] = desiredv_cpus
420 if len(compute_resources) > 0:
421 compute_kwargs["computeResources"] = compute_resources
422 updates = True
423 if updates:
424 try:
425 if not check_mode:
426 update_env_response = client.update_compute_environment(**compute_kwargs)
427 if not update_env_response:
428 module.fail_json(msg="Unable to get compute environment information after creating")
429 changed = True
430 action_taken = "updated"
431 except (BotoCoreError, ClientError) as e:
432 module.fail_json_aws(e, msg="Unable to update environment.")
433
434 else:
435 # Create Batch Compute Environment
436 changed = create_compute_environment(module, client)
437 # Describe compute environment
438 action_taken = "added"
439 response = get_current_compute_environment(module, client)
440 if not response:
441 module.fail_json(msg="Unable to get compute environment information after creating")
442 else:
443 if current_state == "present":
444 # remove the compute environment
445 changed = remove_compute_environment(module, client)
446 action_taken = "deleted"
447 return dict(changed=changed, batch_compute_environment_action=action_taken, response=response)
448
449
450 # ---------------------------------------------------------------------------------------------------
451 #
452 # MAIN
453 #
454 # ---------------------------------------------------------------------------------------------------
455
456
457 def main():
458 """
459 Main entry point.
460
461 :return dict: changed, batch_compute_environment_action, response
462 """
463
464 argument_spec = dict(
465 state=dict(default="present", choices=["present", "absent"]),
466 compute_environment_name=dict(required=True),
467 type=dict(required=True, choices=["MANAGED", "UNMANAGED"]),
468 compute_environment_state=dict(required=False, default="ENABLED", choices=["ENABLED", "DISABLED"]),
469 service_role=dict(required=True),
470 compute_resource_type=dict(required=True, choices=["EC2", "SPOT"]),
471 minv_cpus=dict(type="int", required=True),
472 maxv_cpus=dict(type="int", required=True),
473 desiredv_cpus=dict(type="int"),
474 instance_types=dict(type="list", required=True, elements="str"),
475 image_id=dict(),
476 subnets=dict(type="list", required=True, elements="str"),
477 security_group_ids=dict(type="list", required=True, elements="str"),
478 ec2_key_pair=dict(no_log=False),
479 instance_role=dict(required=True),
480 tags=dict(type="dict"),
481 bid_percentage=dict(type="int"),
482 spot_iam_fleet_role=dict(),
483 )
484
485 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
486
487 client = module.client("batch")
488
489 validate_params(module)
490
491 results = manage_state(module, client)
492
493 module.exit_json(**camel_dict_to_snake_dict(results, ignore_list=["Tags"]))
494
495
496 if __name__ == "__main__":
497 main()