Debian Codegraph @

ansible_collections/netapp/cloudmanager/plugins/modules/na_cloudmanager_aws_fsx.py

raw
1 #!/usr/bin/python
2
3 # (c) 2022, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 '''
7 na_cloudmanager_aws_fsx
8 '''
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14
15 module: na_cloudmanager_aws_fsx
16 short_description: Cloud ONTAP file system(FSx) in AWS
17 extends_documentation_fragment:
18 - netapp.cloudmanager.netapp.cloudmanager
19 version_added: '21.13.0'
20 author: NetApp Ansible Team (@carchi8py) <[email protected]>
21
22 description:
23 - Create or delete CVO/Working Environment for AWS FSx.
24
25 options:
26
27 state:
28 description:
29 - Whether the specified FSx in AWS should exist or not.
30 choices: ['present', 'absent']
31 default: 'present'
32 type: str
33
34 name:
35 required: true
36 description:
37 - The name of the CVO/Working Environment for AWS FSx to manage.
38 type: str
39
40 region:
41 description:
42 - The region where the working environment will be created.
43 type: str
44
45 aws_credentials_name:
46 description:
47 - The name of the AWS Credentials account name.
48 type: str
49
50 workspace_id:
51 description:
52 - The ID of the Cloud Manager workspace of working environment.
53 type: str
54
55 tenant_id:
56 required: true
57 description:
58 - The NetApp account ID that the File System will be associated with.
59 type: str
60
61 working_environment_id:
62 description:
63 - The ID of the AWS FSx working environment used for delete.
64 type: str
65
66 storage_capacity_size:
67 description:
68 - volume size for the first data aggregate.
69 - For GB, the value can be [100 or 500].
70 - For TB, the value can be [1,2,4,8,16].
71 type: int
72
73 storage_capacity_size_unit:
74 description:
75 - The unit for volume size.
76 choices: ['GiB', 'TiB']
77 type: str
78
79 fsx_admin_password:
80 description:
81 - The admin password for Cloud Volumes ONTAP fsxadmin user.
82 type: str
83
84 throughput_capacity:
85 description:
86 - The capacity of the throughput.
87 choices: [512, 1024, 2048]
88 type: int
89
90 security_group_ids:
91 description:
92 - The IDs of the security groups for the working environment, multiple security groups can be provided separated by ','.
93 type: list
94 elements: str
95
96 kms_key_id:
97 description:
98 - AWS encryption parameters. It is required if using aws encryption.
99 type: str
100
101 tags:
102 description:
103 - Additional tags for the FSx AWS working environment.
104 type: list
105 elements: dict
106 suboptions:
107 tag_key:
108 description: The key of the tag.
109 type: str
110 tag_value:
111 description: The tag value.
112 type: str
113
114 primary_subnet_id:
115 description:
116 - The subnet ID of the first node.
117 type: str
118
119 secondary_subnet_id:
120 description:
121 - The subnet ID of the second node.
122 type: str
123
124 route_table_ids:
125 description:
126 - The list of route table IDs that will be updated with the floating IPs.
127 type: list
128 elements: str
129
130 minimum_ssd_iops:
131 description:
132 - Provisioned SSD IOPS.
133 type: int
134
135 endpoint_ip_address_range:
136 description:
137 - The endpoint IP address range.
138 type: str
139
140 import_file_system:
141 description:
142 - bool option to existing import AWS file system to CloudManager.
143 type: bool
144 default: false
145 version_added: 21.17.0
146
147 file_system_id:
148 description:
149 - The AWS file system ID to import to CloudManager. Required when import_file_system is 'True'
150 type: str
151 version_added: 21.17.0
152
153 notes:
154 - Support check_mode.
155 '''
156
157 EXAMPLES = """
158 - name: Create NetApp AWS FSx
159 netapp.cloudmanager.na_cloudmanager_aws_fsx:
160 state: present
161 refresh_token: "{{ xxxxxxxxxxxxxxx }}"
162 name: fsxAnsible
163 region: us-east-2
164 workspace_id: workspace-xxxxx
165 tenant_id: account-xxxxx
166 storage_capacity_size: 1024
167 storage_capacity_size_unit: TiB
168 aws_credentials_name: xxxxxxx
169 primary_subnet_id: subnet-xxxxxx
170 secondary_subnet_id: subnet-xxxxx
171 throughput_capacity: 512
172 fsx_admin_password: xxxxxxx
173 tags: [
174 {tag_key: abcd,
175 tag_value: ABCD}]
176
177 - name: Import AWS FSX
178 na_cloudmanager_aws_fsx:
179 state: present
180 refresh_token: "{{ xxxxxxxxxxxxxxx }}"
181 name: fsxAnsible
182 region: us-west-2
183 workspace_id: workspace-xxxxx
184 import_file_system: True
185 file_system_id: "{{ xxxxxxxxxxxxxxx }}"
186 tenant_id: account-xxxxx
187 aws_credentials_name: xxxxxxx
188
189 - name: Delete NetApp AWS FSx
190 netapp.cloudmanager.na_cloudmanager_aws_fsx:
191 state: absent
192 refresh_token: "{{ xxxxxxxxxxxxxxx }}"
193 working_environment_id: fs-xxxxxx
194 name: fsxAnsible
195 tenant_id: account-xxxxx
196 """
197
198 RETURN = '''
199 working_environment_id:
200 description: Newly created AWS FSx working_environment_id.
201 type: str
202 returned: success
203 '''
204
205 import time
206
207 from ansible.module_utils.basic import AnsibleModule
208 import ansible_collections.netapp.cloudmanager.plugins.module_utils.netapp as netapp_utils
209 from ansible_collections.netapp.cloudmanager.plugins.module_utils.netapp_module import NetAppModule
210 from ansible_collections.netapp.cloudmanager.plugins.module_utils.netapp import CloudManagerRestAPI
211
212
213 class NetAppCloudManagerAWSFSX:
214 ''' object initialize and class methods '''
215
216 def __init__(self):
217 self.use_rest = False
218 self.argument_spec = netapp_utils.cloudmanager_host_argument_spec()
219 self.argument_spec.update(dict(
220 name=dict(required=True, type='str'),
221 state=dict(required=False, choices=['present', 'absent'], default='present'),
222 region=dict(required=False, type='str'),
223 aws_credentials_name=dict(required=False, type='str'),
224 workspace_id=dict(required=False, type='str'),
225 tenant_id=dict(required=True, type='str'),
226 working_environment_id=dict(required=False, type='str'),
227 storage_capacity_size=dict(required=False, type='int'),
228 storage_capacity_size_unit=dict(required=False, type='str', choices=['GiB', 'TiB']),
229 fsx_admin_password=dict(required=False, type='str', no_log=True),
230 throughput_capacity=dict(required=False, type='int', choices=[512, 1024, 2048]),
231 security_group_ids=dict(required=False, type='list', elements='str'),
232 kms_key_id=dict(required=False, type='str', no_log=True),
233 tags=dict(required=False, type='list', elements='dict', options=dict(
234 tag_key=dict(type='str', no_log=False),
235 tag_value=dict(type='str')
236 )),
237 primary_subnet_id=dict(required=False, type='str'),
238 secondary_subnet_id=dict(required=False, type='str'),
239 route_table_ids=dict(required=False, type='list', elements='str'),
240 minimum_ssd_iops=dict(required=False, type='int'),
241 endpoint_ip_address_range=dict(required=False, type='str'),
242 import_file_system=dict(required=False, type='bool', default=False),
243 file_system_id=dict(required=False, type='str'),
244 ))
245
246 self.module = AnsibleModule(
247 argument_spec=self.argument_spec,
248 required_if=[
249 ['state', 'present', ['region', 'aws_credentials_name', 'workspace_id', 'fsx_admin_password', 'throughput_capacity',
250 'primary_subnet_id', 'secondary_subnet_id', 'storage_capacity_size', 'storage_capacity_size_unit']],
251 ['import_file_system', True, ['file_system_id']]
252 ],
253 required_one_of=[['refresh_token', 'sa_client_id']],
254 required_together=[['sa_client_id', 'sa_secret_key'], ['storage_capacity_size', 'storage_capacity_size_unit']],
255 supports_check_mode=True,
256 )
257
258 self.na_helper = NetAppModule()
259 self.parameters = self.na_helper.set_parameters(self.module.params)
260 self.rest_api = CloudManagerRestAPI(self.module)
261 self.rest_api.url += self.rest_api.environment_data['CLOUD_MANAGER_HOST']
262 self.headers = None
263 if self.rest_api.simulator:
264 self.headers = {
265 'x-simulator': 'true'
266 }
267 if self.parameters['state'] == 'present':
268 self.aws_credentials_id, error = self.get_aws_credentials_id()
269 if error is not None:
270 self.module.fail_json(msg=str(error))
271
272 def get_aws_credentials_id(self):
273 """
274 Get aws_credentials_id
275 :return: AWS Credentials ID
276 """
277 api = "/fsx-ontap/aws-credentials/"
278 api += self.parameters['tenant_id']
279 response, error, dummy = self.rest_api.get(api, None, header=self.headers)
280 if error:
281 return response, "Error: getting aws_credentials_id %s" % error
282 for each in response:
283 if each['name'] == self.parameters['aws_credentials_name']:
284 return each['id'], None
285 return None, "Error: aws_credentials_name not found"
286
287 def discover_aws_fsx(self):
288 """
289 discover aws_fsx
290 """
291 api = "/fsx-ontap/working-environments/%s/discover?credentials-id=%s&workspace-id=%s&region=%s"\
292 % (self.parameters['tenant_id'], self.aws_credentials_id, self.parameters['workspace_id'], self.parameters['region'])
293 response, error, dummy = self.rest_api.get(api, None, header=self.headers)
294 if error:
295 return "Error: discovering aws_fsx %s" % error
296 id_found = False
297 for each in response:
298 if each['id'] == self.parameters['file_system_id']:
299 id_found = True
300 break
301 if not id_found:
302 return "Error: file_system_id provided could not be found"
303
304 def recover_aws_fsx(self):
305 """
306 recover aws_fsx
307 """
308 json = {"name": self.parameters['name'],
309 "region": self.parameters['region'],
310 "workspaceId": self.parameters['workspace_id'],
311 "credentialsId": self.aws_credentials_id,
312 "fileSystemId": self.parameters['file_system_id'],
313 }
314 api_url = "/fsx-ontap/working-environments/%s/recover" % self.parameters['tenant_id']
315 response, error, dummy = self.rest_api.post(api_url, json, header=self.headers)
316 if error is not None:
317 self.module.fail_json(
318 msg="Error: unexpected response on recovering AWS FSx: %s, %s" % (error, response))
319
320 def create_aws_fsx(self):
321 """ Create AWS FSx """
322 json = {"name": self.parameters['name'],
323 "region": self.parameters['region'],
324 "workspaceId": self.parameters['workspace_id'],
325 "credentialsId": self.aws_credentials_id,
326 "throughputCapacity": self.parameters['throughput_capacity'],
327 "storageCapacity": {
328 "size": self.parameters['storage_capacity_size'],
329 "unit": self.parameters['storage_capacity_size_unit']},
330 "fsxAdminPassword": self.parameters['fsx_admin_password'],
331 "primarySubnetId": self.parameters['primary_subnet_id'],
332 "secondarySubnetId": self.parameters['secondary_subnet_id'],
333 }
334
335 if self.parameters.get('tags') is not None:
336 tags = []
337 for each_tag in self.parameters['tags']:
338 tag = {
339 'key': each_tag['tag_key'],
340 'value': each_tag['tag_value']
341 }
342
343 tags.append(tag)
344 json.update({"tags": tags})
345
346 if self.parameters.get('security_group_ids'):
347 json.update({"securityGroupIds": self.parameters['security_group_ids']})
348
349 if self.parameters.get('route_table_ids'):
350 json.update({"routeTableIds": self.parameters['route_table_ids']})
351
352 if self.parameters.get('kms_key_id'):
353 json.update({"kmsKeyId": self.parameters['kms_key_id']})
354
355 if self.parameters.get('minimum_ssd_iops'):
356 json.update({"minimumSsdIops": self.parameters['minimum_ssd_iops']})
357
358 if self.parameters.get('endpoint_ip_address_range'):
359 json.update({"endpointIpAddressRange": self.parameters['endpoint_ip_address_range']})
360
361 api_url = '/fsx-ontap/working-environments/%s' % self.parameters['tenant_id']
362 response, error, dummy = self.rest_api.post(api_url, json, header=self.headers)
363 if error is not None:
364 self.module.fail_json(
365 msg="Error: unexpected response on creating AWS FSx: %s, %s" % (str(error), str(response)))
366 working_environment_id = response['id']
367 creation_wait_time = 30
368 creation_retry_count = 30
369 wait_on_completion_api_url = '/fsx-ontap/working-environments/%s/%s?provider-details=true' % (self.parameters['tenant_id'], working_environment_id)
370
371 err = self.wait_on_completion_for_fsx(wait_on_completion_api_url, "AWS_FSX", "create", creation_retry_count, creation_wait_time)
372
373 if err is not None:
374 self.module.fail_json(msg="Error: unexpected response wait_on_completion for creating AWS FSX: %s" % str(err))
375
376 return working_environment_id
377
378 def wait_on_completion_for_fsx(self, api_url, action_name, task, retries, wait_interval):
379 while True:
380 fsx_status, error = self.check_task_status_for_fsx(api_url)
381 if error is not None:
382 return error
383 if fsx_status['status']['status'] == "ON" and fsx_status['status']['lifecycle'] == "AVAILABLE":
384 return None
385 elif fsx_status['status']['status'] == "FAILED":
386 return 'Failed to %s %s' % (task, action_name)
387 if retries == 0:
388 return 'Taking too long for %s to %s or not properly setup' % (action_name, task)
389 time.sleep(wait_interval)
390 retries = retries - 1
391
392 def check_task_status_for_fsx(self, api_url):
393
394 network_retries = 3
395 exponential_retry_time = 1
396 while True:
397 result, error, dummy = self.rest_api.get(api_url, None, header=self.headers)
398 if error is not None:
399 if network_retries > 0:
400 time.sleep(exponential_retry_time)
401 exponential_retry_time *= 2
402 network_retries = network_retries - 1
403 else:
404 return 0, error
405 else:
406 response = result
407 break
408 return response['providerDetails'], None
409
410 def delete_aws_fsx(self, id, tenant_id):
411 """
412 Delete AWS FSx
413 """
414 api_url = '/fsx-ontap/working-environments/%s/%s' % (tenant_id, id)
415 response, error, dummy = self.rest_api.delete(api_url, None, header=self.headers)
416 if error is not None:
417 self.module.fail_json(msg="Error: unexpected response on deleting AWS FSx: %s, %s" % (str(error), str(response)))
418
419 def apply(self):
420 """
421 Apply action to the AWS FSx working Environment
422 :return: None
423 """
424 working_environment_id = None
425 current, error = self.na_helper.get_aws_fsx_details(self.rest_api, header=self.headers)
426 if error is not None:
427 self.module.fail_json(msg="Error: unexpected response on fetching AWS FSx: %s" % str(error))
428 cd_action = self.na_helper.get_cd_action(current, self.parameters)
429 if self.parameters['import_file_system'] and cd_action == "create":
430 error = self.discover_aws_fsx()
431 if error is not None:
432 self.module.fail_json(msg="Error: unexpected response on discovering AWS FSx: %s" % str(error))
433 cd_action = "import"
434 self.na_helper.changed = True
435
436 if self.na_helper.changed and not self.module.check_mode:
437 if cd_action == "import":
438 self.recover_aws_fsx()
439 working_environment_id = self.parameters['file_system_id']
440 elif cd_action == "create":
441 working_environment_id = self.create_aws_fsx()
442 elif cd_action == "delete":
443 self.delete_aws_fsx(current['id'], self.parameters['tenant_id'])
444
445 self.module.exit_json(changed=self.na_helper.changed, working_environment_id=working_environment_id)
446
447
448 def main():
449 """
450 Create AWS FSx class instance and invoke apply
451 :return: None
452 """
453 obj_store = NetAppCloudManagerAWSFSX()
454 obj_store.apply()
455
456
457 if __name__ == '__main__':
458 main()