Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vsphere_file.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Dag Wieers (@dagwieers) <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: vsphere_file
15 short_description: Manage files on a vCenter datastore
16 description:
17 - Manage files on a vCenter datastore.
18 author:
19 - Dag Wieers (@dagwieers)
20 options:
21 datacenter:
22 description:
23 - The datacenter on the vCenter server that holds the datastore.
24 type: str
25 required: true
26 datastore:
27 description:
28 - The datastore on the vCenter server to push files to.
29 type: str
30 required: true
31 path:
32 description:
33 - The file or directory on the datastore on the vCenter server.
34 type: str
35 required: true
36 aliases: [ dest ]
37 timeout:
38 description:
39 - The timeout in seconds for the upload to the datastore.
40 type: int
41 default: 10
42 state:
43 description:
44 - The state of or the action on the provided path.
45 - If V(absent), the file will be removed.
46 - If V(directory), the directory will be created.
47 - If V(file), more information of the (existing) file will be returned.
48 - If V(touch), an empty file will be created if the path does not exist.
49 type: str
50 choices: [ absent, directory, file, touch ]
51 default: file
52 notes:
53 - The vSphere folder API does not allow to remove directory objects.
54 extends_documentation_fragment:
55 - vmware.vmware.base_options
56 '''
57
58 EXAMPLES = r'''
59 - name: Create an empty file on a datastore
60 community.vmware.vsphere_file:
61 hostname: '{{ vhost }}'
62 username: '{{ vuser }}'
63 password: '{{ vpass }}'
64 datacenter: DC1 Someplace
65 datastore: datastore1
66 path: some/remote/file
67 state: touch
68 delegate_to: localhost
69
70 - name: Create a directory on a datastore
71 community.vmware.vsphere_file:
72 hostname: '{{ vhost }}'
73 username: '{{ vuser }}'
74 password: '{{ vpass }}'
75 datacenter: DC2 Someplace
76 datastore: datastore2
77 path: other/remote/file
78 state: directory
79 delegate_to: localhost
80
81 - name: Query a file on a datastore
82 community.vmware.vsphere_file:
83 hostname: '{{ vhost }}'
84 username: '{{ vuser }}'
85 password: '{{ vpass }}'
86 datacenter: DC1 Someplace
87 datastore: datastore1
88 path: some/remote/file
89 state: file
90 delegate_to: localhost
91 ignore_errors: true
92
93 - name: Delete a file on a datastore
94 community.vmware.vsphere_file:
95 hostname: '{{ vhost }}'
96 username: '{{ vuser }}'
97 password: '{{ vpass }}'
98 datacenter: DC2 Someplace
99 datastore: datastore2
100 path: other/remote/file
101 state: absent
102 delegate_to: localhost
103 '''
104
105 RETURN = r'''
106 '''
107
108 import socket
109
110 from ansible.module_utils.basic import AnsibleModule
111 from urllib.error import HTTPError
112 from urllib.parse import quote, urlencode
113 from ansible.module_utils.urls import open_url
114 from ansible.module_utils.common.text.converters import to_native
115 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
116
117
118 def vmware_path(datastore, datacenter, path):
119 ''' Constructs a URL path that VSphere accepts reliably '''
120 path = '/folder/{path}'.format(path=quote(path.strip('/')))
121 # Due to a software bug in vSphere, it fails to handle ampersand in datacenter names
122 # The solution is to do what vSphere does (when browsing) and double-encode ampersands, maybe others ?
123 datacenter = datacenter.replace('&', '%26')
124 if not path.startswith('/'):
125 path = '/' + path
126 params = dict(dsName=datastore)
127 if datacenter:
128 params['dcPath'] = datacenter
129 return '{0}?{1}'.format(path, urlencode(params))
130
131
132 def main():
133
134 argument_spec = base_argument_spec()
135
136 argument_spec.update(dict(
137 datacenter=dict(type='str', required=True),
138 datastore=dict(type='str', required=True),
139 path=dict(type='str', required=True, aliases=['dest']),
140 state=dict(type='str', default='file', choices=['absent', 'directory', 'file', 'touch']),
141 timeout=dict(type='int', default=10),
142 ))
143
144 module = AnsibleModule(
145 argument_spec=argument_spec,
146 supports_check_mode=True,
147 )
148
149 host = module.params.get('hostname')
150 username = module.params.get('username')
151 password = module.params.get('password')
152 datacenter = module.params.get('datacenter')
153 datastore = module.params.get('datastore')
154 path = module.params.get('path')
155 validate_certs = module.params.get('validate_certs')
156 timeout = module.params.get('timeout')
157 state = module.params.get('state')
158
159 remote_path = vmware_path(datastore, datacenter, path)
160 url = 'https://%s%s' % (host, remote_path)
161
162 result = dict(
163 path=path,
164 size=None,
165 state=state,
166 status=None,
167 url=url,
168 )
169
170 # Check if the file/directory exists
171 try:
172 r = open_url(url, method='HEAD', timeout=timeout,
173 url_username=username, url_password=password,
174 validate_certs=validate_certs, force_basic_auth=True)
175 except HTTPError as e:
176 r = e
177 except socket.error as e:
178 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
179 except Exception as e:
180 module.fail_json(msg=to_native(e), errno=dir(e), reason=to_native(e), **result)
181
182 status = r.getcode()
183 if status == 200:
184 exists = True
185 result['size'] = int(r.headers.get('content-length', None))
186 elif status == 404:
187 exists = False
188 else:
189 result['reason'] = r.msg
190 result['status'] = status
191 module.fail_json(msg="Failed to query for file '%s'" % path, errno=None, headers=dict(r.headers), **result)
192
193 if state == 'absent':
194 if not exists:
195 module.exit_json(changed=False, **result)
196
197 if module.check_mode:
198 result['reason'] = 'No Content'
199 result['status'] = 204
200 else:
201 try:
202 r = open_url(url, method='DELETE', timeout=timeout,
203 url_username=username, url_password=password,
204 validate_certs=validate_certs, force_basic_auth=True)
205 except HTTPError as e:
206 r = e
207 except socket.error as e:
208 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
209 except Exception as e:
210 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
211
212 result['reason'] = r.msg
213 result['status'] = r.getcode()
214
215 if result['status'] == 405:
216 result['state'] = 'directory'
217 module.fail_json(msg='Directories cannot be removed with this module', errno=None, headers=dict(r.headers), **result)
218 elif result['status'] != 204:
219 module.fail_json(msg="Failed to remove '%s'" % path, errno=None, headers=dict(r.headers), **result)
220
221 result['size'] = None
222 module.exit_json(changed=True, **result)
223
224 # NOTE: Creating a file in a non-existing directory, then remove the file
225 elif state == 'directory':
226 if exists:
227 module.exit_json(changed=False, **result)
228
229 if module.check_mode:
230 result['reason'] = 'Created'
231 result['status'] = 201
232 else:
233 # Create a temporary file in the new directory
234 remote_path = vmware_path(datastore, datacenter, path + '/foobar.tmp')
235 temp_url = 'https://%s%s' % (host, remote_path)
236
237 try:
238 r = open_url(temp_url, method='PUT', timeout=timeout,
239 url_username=username, url_password=password,
240 validate_certs=validate_certs, force_basic_auth=True)
241 except HTTPError as e:
242 r = e
243 except socket.error as e:
244 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
245 except Exception as e:
246 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
247
248 result['reason'] = r.msg
249 result['status'] = r.getcode()
250 if result['status'] != 201:
251 result['url'] = temp_url
252 module.fail_json(msg='Failed to create temporary file', errno=None, headers=dict(r.headers), **result)
253
254 try:
255 r = open_url(temp_url, method='DELETE', timeout=timeout,
256 url_username=username, url_password=password,
257 validate_certs=validate_certs, force_basic_auth=True)
258 except HTTPError as e:
259 r = e
260 except socket.error as e:
261 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
262 except Exception as e:
263 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
264
265 status = r.getcode()
266 if status != 204:
267 result['reason'] = r.msg
268 result['status'] = status
269 module.warn('Failed to remove temporary file ({reason})'.format(**result))
270
271 module.exit_json(changed=True, **result)
272
273 elif state == 'file':
274
275 if not exists:
276 result['state'] = 'absent'
277 result['status'] = status
278 module.fail_json(msg="File '%s' is absent, cannot continue" % path, **result)
279
280 result['status'] = status
281 module.exit_json(changed=False, **result)
282
283 elif state == 'touch':
284 if exists:
285 result['state'] = 'file'
286 module.exit_json(changed=False, **result)
287
288 if module.check_mode:
289 result['reason'] = 'Created'
290 result['status'] = 201
291 else:
292 try:
293 r = open_url(url, method='PUT', timeout=timeout,
294 url_username=username, url_password=password,
295 validate_certs=validate_certs, force_basic_auth=True)
296 except HTTPError as e:
297 r = e
298 except socket.error as e:
299 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
300 except Exception as e:
301 module.fail_json(msg=to_native(e), errno=e[0], reason=to_native(e), **result)
302
303 result['reason'] = r.msg
304 result['status'] = r.getcode()
305 if result['status'] != 201:
306 module.fail_json(msg="Failed to touch '%s'" % path, errno=None, headers=dict(r.headers), **result)
307
308 result['size'] = 0
309 result['state'] = 'file'
310 module.exit_json(changed=True, **result)
311
312
313 if __name__ == '__main__':
314 main()