Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: 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: efs
10 version_added: 1.0.0
11 short_description: create and maintain EFS file systems
12 description:
13 - Module allows create, search and destroy Amazon EFS file systems.
14 author:
15 - "Ryan Sydnor (@ryansydnor)"
16 - "Artem Kazakov (@akazakov)"
17 options:
18 encrypt:
19 description:
20 - If I(encrypt=true) creates an encrypted file system. This can not be modified after the file system is created.
21 type: bool
22 default: false
23 kms_key_id:
24 description:
25 - The id of the AWS KMS CMK that will be used to protect the encrypted file system. This parameter is only
26 required if you want to use a non-default CMK. If this parameter is not specified, the default CMK for
27 Amazon EFS is used. The key id can be Key ID, Key ID ARN, Key Alias or Key Alias ARN.
28 type: str
29 state:
30 description:
31 - Allows to create, search and destroy Amazon EFS file system.
32 default: 'present'
33 choices: ['present', 'absent']
34 type: str
35 name:
36 description:
37 - Creation Token of Amazon EFS file system. Required for create and update. Either name or ID required for delete.
38 type: str
39 id:
40 description:
41 - ID of Amazon EFS. Either name or ID required for delete.
42 type: str
43 performance_mode:
44 description:
45 - File system's performance mode to use. Only takes effect during creation.
46 default: 'general_purpose'
47 choices: ['general_purpose', 'max_io']
48 type: str
49 tags:
50 description:
51 - "List of tags of Amazon EFS. Should be defined as dictionary
52 In case of 'present' state with list of tags and existing EFS (matched by 'name'), tags of EFS will be replaced with provided data."
53 type: dict
54 targets:
55 description:
56 - "List of mounted targets. It should be a list of dictionaries, every dictionary should include next attributes:
57 This data may be modified for existing EFS using state 'present' and new list of mount targets."
58 type: list
59 elements: dict
60 default: []
61 suboptions:
62 subnet_id:
63 required: true
64 description: The ID of the subnet to add the mount target in.
65 ip_address:
66 type: str
67 description: A valid IPv4 address within the address range of the specified subnet.
68 security_groups:
69 type: list
70 elements: str
71 description: List of security group IDs, of the form 'sg-xxxxxxxx'. These must be for the same VPC as subnet specified
72 throughput_mode:
73 description:
74 - The throughput_mode for the file system to be created.
75 choices: ['bursting', 'provisioned']
76 type: str
77 provisioned_throughput_in_mibps:
78 description:
79 - If the throughput_mode is provisioned, select the amount of throughput to provisioned in Mibps.
80 type: float
81 wait:
82 description:
83 - "In case of 'present' state should wait for EFS 'available' life cycle state (of course, if current state not 'deleting' or 'deleted')
84 In case of 'absent' state should wait for EFS 'deleted' life cycle state"
85 type: bool
86 default: false
87 wait_timeout:
88 description:
89 - How long the module should wait (in seconds) for desired state before returning. Zero means wait as long as necessary.
90 default: 0
91 type: int
92 transition_to_ia:
93 description:
94 - How many days before objects transition to the lower-cost EFS Infrequent Access (IA) storage class.
95 - If set to the string C(None), any existing lifecyle policy will be removed, and objects will not transition
96 to an IA storage class.
97 - If this parameter is absent, any existing lifecycle policy will not be affected.
98 choices: ['None', '7', '14', '30', '60', '90']
99 type: str
100 version_added: 2.1.0
101
102 extends_documentation_fragment:
103 - amazon.aws.common.modules
104 - amazon.aws.region.modules
105 - amazon.aws.tags
106 - amazon.aws.boto3
107 """
108
109 EXAMPLES = r"""
110 - name: EFS provisioning
111 community.aws.efs:
112 state: present
113 name: myTestEFS
114 tags:
115 Name: myTestNameTag
116 purpose: file-storage
117 targets:
118 - subnet_id: subnet-748c5d03
119 security_groups: ["sg-1a2b3c4d"]
120
121 - name: Modifying EFS data
122 community.aws.efs:
123 state: present
124 name: myTestEFS
125 tags:
126 name: myAnotherTestTag
127 targets:
128 - subnet_id: subnet-7654fdca
129 security_groups: ["sg-4c5d6f7a"]
130
131 - name: Set a lifecycle policy
132 community.aws.efs:
133 state: present
134 name: myTestEFS
135 transition_to_ia: 7
136 targets:
137 - subnet_id: subnet-7654fdca
138 security_groups: ["sg-4c5d6f7a"]
139
140 - name: Remove a lifecycle policy
141 community.aws.efs:
142 state: present
143 name: myTestEFS
144 transition_to_ia: None
145 targets:
146 - subnet_id: subnet-7654fdca
147 security_groups: ["sg-4c5d6f7a"]
148
149 - name: Deleting EFS
150 community.aws.efs:
151 state: absent
152 name: myTestEFS
153 """
154
155 RETURN = r"""
156 creation_time:
157 description: timestamp of creation date
158 returned: always
159 type: str
160 sample: "2015-11-16 07:30:57-05:00"
161 creation_token:
162 description: EFS creation token
163 returned: always
164 type: str
165 sample: "console-88609e04-9a0e-4a2e-912c-feaa99509961"
166 file_system_id:
167 description: ID of the file system
168 returned: always
169 type: str
170 sample: "fs-xxxxxxxx"
171 life_cycle_state:
172 description: state of the EFS file system
173 returned: always
174 type: str
175 sample: "creating, available, deleting, deleted"
176 mount_point:
177 description: url of file system with leading dot from the time when AWS EFS required to add a region suffix to the address
178 returned: always
179 type: str
180 sample: ".fs-xxxxxxxx.efs.us-west-2.amazonaws.com:/"
181 filesystem_address:
182 description: url of file system valid for use with mount
183 returned: always
184 type: str
185 sample: "fs-xxxxxxxx.efs.us-west-2.amazonaws.com:/"
186 mount_targets:
187 description: list of mount targets
188 returned: always
189 type: list
190 sample:
191 [
192 {
193 "file_system_id": "fs-a7ad440e",
194 "ip_address": "172.31.17.173",
195 "life_cycle_state": "available",
196 "mount_target_id": "fsmt-d8907871",
197 "network_interface_id": "eni-6e387e26",
198 "owner_id": "123456789012",
199 "security_groups": [
200 "sg-a30b22c6"
201 ],
202 "subnet_id": "subnet-e265c895"
203 },
204 ...
205 ]
206 name:
207 description: name of the file system
208 returned: always
209 type: str
210 sample: "my-efs"
211 number_of_mount_targets:
212 description: the number of targets mounted
213 returned: always
214 type: int
215 sample: 3
216 owner_id:
217 description: AWS account ID of EFS owner
218 returned: always
219 type: str
220 sample: "XXXXXXXXXXXX"
221 size_in_bytes:
222 description: size of the file system in bytes as of a timestamp
223 returned: always
224 type: dict
225 sample:
226 {
227 "timestamp": "2015-12-21 13:59:59-05:00",
228 "value": 12288
229 }
230 performance_mode:
231 description: performance mode of the file system
232 returned: always
233 type: str
234 sample: "generalPurpose"
235 tags:
236 description: tags on the efs instance
237 returned: always
238 type: dict
239 sample:
240 {
241 "name": "my-efs",
242 "key": "Value"
243 }
244 """
245
246 from time import sleep
247 from time import time as timestamp
248
249 try:
250 import botocore
251 except ImportError:
252 pass # Handled by AnsibleAWSModule
253
254 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
255
256 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
257 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
258 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
259 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
260
261 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
262
263
264 def _index_by_key(key, items):
265 return dict((item[key], item) for item in items)
266
267
268 class EFSConnection(object):
269 DEFAULT_WAIT_TIMEOUT_SECONDS = 0
270
271 STATE_CREATING = "creating"
272 STATE_AVAILABLE = "available"
273 STATE_DELETING = "deleting"
274 STATE_DELETED = "deleted"
275
276 def __init__(self, module):
277 self.connection = module.client("efs")
278 region = module.region
279
280 self.module = module
281 self.region = region
282 self.wait = module.params.get("wait")
283 self.wait_timeout = module.params.get("wait_timeout")
284
285 def get_file_systems(self, **kwargs):
286 """
287 Returns generator of file systems including all attributes of FS
288 """
289 items = iterate_all(
290 "FileSystems",
291 self.connection.describe_file_systems,
292 **kwargs,
293 )
294 for item in items:
295 item["Name"] = item["CreationToken"]
296 item["CreationTime"] = str(item["CreationTime"])
297
298 # In the time when MountPoint was introduced there was a need to add a suffix of network path before one could use it
299 # AWS updated it and now there is no need to add a suffix. MountPoint is left for back-compatibility purpose
300 # And new FilesystemAddress variable is introduced for direct use with other modules (e.g. mount)
301 # AWS documentation is available here:
302 # https://docs.aws.amazon.com/efs/latest/ug/gs-step-three-connect-to-ec2-instance.html
303
304 item["MountPoint"] = f".{item['FileSystemId']}.efs.{self.region}.amazonaws.com:/"
305 item["FilesystemAddress"] = f"{item['FileSystemId']}.efs.{self.region}.amazonaws.com:/"
306 if "Timestamp" in item["SizeInBytes"]:
307 item["SizeInBytes"]["Timestamp"] = str(item["SizeInBytes"]["Timestamp"])
308 if item["LifeCycleState"] == self.STATE_AVAILABLE:
309 item["Tags"] = self.get_tags(FileSystemId=item["FileSystemId"])
310 item["MountTargets"] = list(self.get_mount_targets(FileSystemId=item["FileSystemId"]))
311 else:
312 item["Tags"] = {}
313 item["MountTargets"] = []
314 yield item
315
316 def get_tags(self, **kwargs):
317 """
318 Returns tag list for selected instance of EFS
319 """
320 tags = self.connection.describe_tags(**kwargs)["Tags"]
321 return tags
322
323 def get_mount_targets(self, **kwargs):
324 """
325 Returns mount targets for selected instance of EFS
326 """
327 targets = iterate_all(
328 "MountTargets",
329 self.connection.describe_mount_targets,
330 **kwargs,
331 )
332 for target in targets:
333 if target["LifeCycleState"] == self.STATE_AVAILABLE:
334 target["SecurityGroups"] = list(self.get_security_groups(MountTargetId=target["MountTargetId"]))
335 else:
336 target["SecurityGroups"] = []
337 yield target
338
339 def get_security_groups(self, **kwargs):
340 """
341 Returns security groups for selected instance of EFS
342 """
343 return iterate_all(
344 "SecurityGroups",
345 self.connection.describe_mount_target_security_groups,
346 **kwargs,
347 )
348
349 def get_file_system_id(self, name):
350 """
351 Returns ID of instance by instance name
352 """
353 info = first_or_default(
354 iterate_all(
355 "FileSystems",
356 self.connection.describe_file_systems,
357 CreationToken=name,
358 )
359 )
360 return info and info["FileSystemId"] or None
361
362 def get_file_system_state(self, name, file_system_id=None):
363 """
364 Returns state of filesystem by EFS id/name
365 """
366 info = first_or_default(
367 iterate_all(
368 "FileSystems",
369 self.connection.describe_file_systems,
370 CreationToken=name,
371 FileSystemId=file_system_id,
372 )
373 )
374 return info and info["LifeCycleState"] or self.STATE_DELETED
375
376 def get_mount_targets_in_state(self, file_system_id, states=None):
377 """
378 Returns states of mount targets of selected EFS with selected state(s) (optional)
379 """
380 targets = iterate_all(
381 "MountTargets",
382 self.connection.describe_mount_targets,
383 FileSystemId=file_system_id,
384 )
385
386 if states:
387 if not isinstance(states, list):
388 states = [states]
389 targets = filter(lambda target: target["LifeCycleState"] in states, targets)
390
391 return list(targets)
392
393 def get_throughput_mode(self, **kwargs):
394 """
395 Returns throughput mode for selected EFS instance
396 """
397 info = first_or_default(
398 iterate_all(
399 "FileSystems",
400 self.connection.describe_file_systems,
401 **kwargs,
402 )
403 )
404
405 return info and info["ThroughputMode"] or None
406
407 def get_provisioned_throughput_in_mibps(self, **kwargs):
408 """
409 Returns throughput mode for selected EFS instance
410 """
411 info = first_or_default(
412 iterate_all(
413 "FileSystems",
414 self.connection.describe_file_systems,
415 **kwargs,
416 )
417 )
418 return info.get("ProvisionedThroughputInMibps", None)
419
420 def create_file_system(
421 self, name, performance_mode, encrypt, kms_key_id, throughput_mode, provisioned_throughput_in_mibps
422 ):
423 """
424 Creates new filesystem with selected name
425 """
426 changed = False
427 state = self.get_file_system_state(name)
428 params = {}
429 params["CreationToken"] = name
430 params["PerformanceMode"] = performance_mode
431 if encrypt:
432 params["Encrypted"] = encrypt
433 if kms_key_id is not None:
434 params["KmsKeyId"] = kms_key_id
435 if throughput_mode:
436 params["ThroughputMode"] = throughput_mode
437 if provisioned_throughput_in_mibps:
438 params["ProvisionedThroughputInMibps"] = provisioned_throughput_in_mibps
439
440 if state in [self.STATE_DELETING, self.STATE_DELETED]:
441 wait_for(
442 lambda: self.get_file_system_state(name),
443 self.STATE_DELETED,
444 )
445 try:
446 self.connection.create_file_system(**params)
447 changed = True
448 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
449 self.module.fail_json_aws(e, msg="Unable to create file system.")
450
451 # we always wait for the state to be available when creating.
452 # if we try to take any actions on the file system before it's available
453 # we'll throw errors
454 wait_for(
455 lambda: self.get_file_system_state(name),
456 self.STATE_AVAILABLE,
457 self.wait_timeout,
458 )
459
460 return changed
461
462 def update_file_system(self, name, throughput_mode, provisioned_throughput_in_mibps):
463 """
464 Update filesystem with new throughput settings
465 """
466 changed = False
467 state = self.get_file_system_state(name)
468 if state in [self.STATE_AVAILABLE, self.STATE_CREATING]:
469 fs_id = self.get_file_system_id(name)
470 current_mode = self.get_throughput_mode(FileSystemId=fs_id)
471 current_throughput = self.get_provisioned_throughput_in_mibps(FileSystemId=fs_id)
472 params = dict()
473 if throughput_mode and throughput_mode != current_mode:
474 params["ThroughputMode"] = throughput_mode
475 if provisioned_throughput_in_mibps and provisioned_throughput_in_mibps != current_throughput:
476 params["ProvisionedThroughputInMibps"] = provisioned_throughput_in_mibps
477 if len(params) > 0:
478 wait_for(
479 lambda: self.get_file_system_state(name),
480 self.STATE_AVAILABLE,
481 self.wait_timeout,
482 )
483 try:
484 self.connection.update_file_system(FileSystemId=fs_id, **params)
485 changed = True
486 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
487 self.module.fail_json_aws(e, msg="Unable to update file system.")
488 return changed
489
490 def update_lifecycle_policy(self, name, transition_to_ia):
491 """
492 Update filesystem with new lifecycle policy.
493 """
494 changed = False
495 state = self.get_file_system_state(name)
496 if state in [self.STATE_AVAILABLE, self.STATE_CREATING]:
497 fs_id = self.get_file_system_id(name)
498 current_policies = self.connection.describe_lifecycle_configuration(FileSystemId=fs_id)
499 if transition_to_ia == "None":
500 LifecyclePolicies = []
501 else:
502 LifecyclePolicies = [{"TransitionToIA": "AFTER_" + transition_to_ia + "_DAYS"}]
503 if current_policies.get("LifecyclePolicies") != LifecyclePolicies:
504 self.connection.put_lifecycle_configuration(
505 FileSystemId=fs_id,
506 LifecyclePolicies=LifecyclePolicies,
507 )
508 changed = True
509 return changed
510
511 def converge_file_system(self, name, tags, purge_tags, targets, throughput_mode, provisioned_throughput_in_mibps):
512 """
513 Change attributes (mount targets and tags) of filesystem by name
514 """
515 result = False
516 fs_id = self.get_file_system_id(name)
517
518 if tags is not None:
519 tags_need_modify, tags_to_delete = compare_aws_tags(
520 boto3_tag_list_to_ansible_dict(self.get_tags(FileSystemId=fs_id)), tags, purge_tags
521 )
522
523 if tags_to_delete:
524 try:
525 self.connection.delete_tags(FileSystemId=fs_id, TagKeys=tags_to_delete)
526 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
527 self.module.fail_json_aws(e, msg="Unable to delete tags.")
528
529 result = True
530
531 if tags_need_modify:
532 try:
533 self.connection.create_tags(
534 FileSystemId=fs_id, Tags=ansible_dict_to_boto3_tag_list(tags_need_modify)
535 )
536 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
537 self.module.fail_json_aws(e, msg="Unable to create tags.")
538
539 result = True
540
541 if targets is not None:
542 incomplete_states = [self.STATE_CREATING, self.STATE_DELETING]
543 wait_for(
544 lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)),
545 0,
546 )
547 current_targets = _index_by_key("SubnetId", self.get_mount_targets(FileSystemId=fs_id))
548 targets = _index_by_key("SubnetId", targets)
549
550 targets_to_create, intersection, targets_to_delete = dict_diff(current_targets, targets, True)
551
552 # To modify mount target it should be deleted and created again
553 changed = [
554 sid
555 for sid in intersection
556 if not targets_equal(
557 ["SubnetId", "IpAddress", "NetworkInterfaceId"], current_targets[sid], targets[sid]
558 )
559 ]
560 targets_to_delete = list(targets_to_delete) + changed
561 targets_to_create = list(targets_to_create) + changed
562
563 if targets_to_delete:
564 for sid in targets_to_delete:
565 self.connection.delete_mount_target(MountTargetId=current_targets[sid]["MountTargetId"])
566 wait_for(
567 lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)),
568 0,
569 )
570 result = True
571
572 if targets_to_create:
573 for sid in targets_to_create:
574 self.connection.create_mount_target(FileSystemId=fs_id, **targets[sid])
575 wait_for(
576 lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)),
577 0,
578 self.wait_timeout,
579 )
580 result = True
581
582 # If no security groups were passed into the module, then do not change it.
583 security_groups_to_update = [
584 sid
585 for sid in intersection
586 if "SecurityGroups" in targets[sid]
587 and current_targets[sid]["SecurityGroups"] != targets[sid]["SecurityGroups"]
588 ]
589
590 if security_groups_to_update:
591 for sid in security_groups_to_update:
592 self.connection.modify_mount_target_security_groups(
593 MountTargetId=current_targets[sid]["MountTargetId"],
594 SecurityGroups=targets[sid].get("SecurityGroups", None),
595 )
596 result = True
597
598 return result
599
600 def delete_file_system(self, name, file_system_id=None):
601 """
602 Removes EFS instance by id/name
603 """
604 result = False
605 state = self.get_file_system_state(name, file_system_id)
606 if state in [self.STATE_CREATING, self.STATE_AVAILABLE]:
607 wait_for(
608 lambda: self.get_file_system_state(name),
609 self.STATE_AVAILABLE,
610 )
611 if not file_system_id:
612 file_system_id = self.get_file_system_id(name)
613 self.delete_mount_targets(file_system_id)
614 self.connection.delete_file_system(FileSystemId=file_system_id)
615 result = True
616
617 if self.wait:
618 wait_for(
619 lambda: self.get_file_system_state(name),
620 self.STATE_DELETED,
621 self.wait_timeout,
622 )
623
624 return result
625
626 def delete_mount_targets(self, file_system_id):
627 """
628 Removes mount targets by EFS id
629 """
630 wait_for(
631 lambda: len(self.get_mount_targets_in_state(file_system_id, self.STATE_CREATING)),
632 0,
633 )
634
635 targets = self.get_mount_targets_in_state(file_system_id, self.STATE_AVAILABLE)
636 for target in targets:
637 self.connection.delete_mount_target(MountTargetId=target["MountTargetId"])
638
639 wait_for(
640 lambda: len(self.get_mount_targets_in_state(file_system_id, self.STATE_DELETING)),
641 0,
642 )
643
644 return len(targets) > 0
645
646
647 def iterate_all(attr, map_method, **kwargs):
648 """
649 Method creates iterator from result set
650 """
651 args = dict((key, value) for (key, value) in kwargs.items() if value is not None)
652 wait = 1
653 while True:
654 try:
655 data = map_method(**args)
656 yield from data[attr]
657 if "NextMarker" in data:
658 args["Marker"] = data["Nextmarker"]
659 continue
660 break
661 except is_boto3_error_code("ThrottlingException"):
662 if wait < 600:
663 sleep(wait)
664 wait = wait * 2
665 continue
666 raise
667
668
669 def targets_equal(keys, a, b):
670 """
671 Method compare two mount targets by specified attributes
672 """
673 for key in keys:
674 if key in b and a[key] != b[key]:
675 return False
676
677 return True
678
679
680 def dict_diff(dict1, dict2, by_key=False):
681 """
682 Helper method to calculate difference of two dictionaries
683 """
684 keys1 = set(dict1.keys() if by_key else dict1.items())
685 keys2 = set(dict2.keys() if by_key else dict2.items())
686
687 intersection = keys1 & keys2
688
689 return keys2 ^ intersection, intersection, keys1 ^ intersection
690
691
692 def first_or_default(items, default=None):
693 """
694 Helper method to fetch first element of list (if exists)
695 """
696 for item in items:
697 return item
698 return default
699
700
701 def wait_for(callback, value, timeout=EFSConnection.DEFAULT_WAIT_TIMEOUT_SECONDS):
702 """
703 Helper method to wait for desired value returned by callback method
704 """
705 wait_start = timestamp()
706 while True:
707 if callback() != value:
708 if timeout != 0 and (timestamp() - wait_start > timeout):
709 raise RuntimeError("Wait timeout exceeded (" + str(timeout) + " sec)")
710 else:
711 sleep(5)
712 continue
713 break
714
715
716 def main():
717 """
718 Module action handler
719 """
720 argument_spec = dict(
721 encrypt=dict(required=False, type="bool", default=False),
722 state=dict(required=False, type="str", choices=["present", "absent"], default="present"),
723 kms_key_id=dict(required=False, type="str", default=None),
724 purge_tags=dict(default=True, type="bool"),
725 id=dict(required=False, type="str", default=None),
726 name=dict(required=False, type="str", default=None),
727 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
728 targets=dict(required=False, type="list", default=[], elements="dict"),
729 performance_mode=dict(
730 required=False, type="str", choices=["general_purpose", "max_io"], default="general_purpose"
731 ),
732 transition_to_ia=dict(required=False, type="str", choices=["None", "7", "14", "30", "60", "90"], default=None),
733 throughput_mode=dict(required=False, type="str", choices=["bursting", "provisioned"], default=None),
734 provisioned_throughput_in_mibps=dict(required=False, type="float"),
735 wait=dict(required=False, type="bool", default=False),
736 wait_timeout=dict(required=False, type="int", default=0),
737 )
738
739 module = AnsibleAWSModule(argument_spec=argument_spec)
740
741 connection = EFSConnection(module)
742
743 name = module.params.get("name")
744 fs_id = module.params.get("id")
745 tags = module.params.get("tags")
746 target_translations = {
747 "ip_address": "IpAddress",
748 "security_groups": "SecurityGroups",
749 "subnet_id": "SubnetId",
750 }
751 targets = [
752 dict((target_translations[key], value) for (key, value) in x.items()) for x in module.params.get("targets")
753 ]
754 performance_mode_translations = {
755 "general_purpose": "generalPurpose",
756 "max_io": "maxIO",
757 }
758 encrypt = module.params.get("encrypt")
759 kms_key_id = module.params.get("kms_key_id")
760 performance_mode = performance_mode_translations[module.params.get("performance_mode")]
761 purge_tags = module.params.get("purge_tags")
762 transition_to_ia = module.params.get("transition_to_ia")
763 throughput_mode = module.params.get("throughput_mode")
764 provisioned_throughput_in_mibps = module.params.get("provisioned_throughput_in_mibps")
765 state = str(module.params.get("state")).lower()
766 changed = False
767
768 if state == "present":
769 if not name:
770 module.fail_json(msg="Name parameter is required for create")
771
772 changed = connection.create_file_system(
773 name, performance_mode, encrypt, kms_key_id, throughput_mode, provisioned_throughput_in_mibps
774 )
775 changed = connection.update_file_system(name, throughput_mode, provisioned_throughput_in_mibps) or changed
776 changed = (
777 connection.converge_file_system(
778 name=name,
779 tags=tags,
780 purge_tags=purge_tags,
781 targets=targets,
782 throughput_mode=throughput_mode,
783 provisioned_throughput_in_mibps=provisioned_throughput_in_mibps,
784 )
785 or changed
786 )
787 if transition_to_ia:
788 changed |= connection.update_lifecycle_policy(name, transition_to_ia)
789 result = first_or_default(connection.get_file_systems(CreationToken=name))
790
791 elif state == "absent":
792 if not name and not fs_id:
793 module.fail_json(msg="Either name or id parameter is required for delete")
794
795 changed = connection.delete_file_system(name, fs_id)
796 result = None
797 if result:
798 result = camel_dict_to_snake_dict(result)
799 module.exit_json(changed=changed, efs=result)
800
801
802 if __name__ == "__main__":
803 main()