Debian Codegraph @

ansible_collections/cisco/mso/plugins/modules/mso_backup.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2020, Shreyas Srish (@shrsr) <[email protected]>
5 # Copyright: (c) 2023, Lionel Hercot (@lhercot) <[email protected]>
6 # Copyright: (c) 2023, Sabari Jaganathan (@sajagana) <[email protected]>
7 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import absolute_import, division, print_function
10
11 __metaclass__ = type
12
13 ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}
14
15 DOCUMENTATION = r"""
16 ---
17 module: mso_backup
18 short_description: Manages backups
19 description:
20 - Manage backups on Cisco ACI Multi-Site.
21 author:
22 - Shreyas Srish (@shrsr)
23 - Lionel Hercot (@lhercot)
24 - Sabari Jaganathan (@sajagana)
25 options:
26 location_type:
27 description:
28 - The type of location for the backup to be stored
29 type: str
30 choices: [ local, remote]
31 default: local
32 backup:
33 description:
34 - The name given to the backup
35 - C(backup) is mutually exclusive with C(backup_id). Only use one of the two.
36 type: str
37 aliases: [ name ]
38 backup_id:
39 description:
40 - The id of a specific backup
41 - C(backup_id) is mutually exclusive with C(backup). Only use one of the two.
42 type: str
43 aliases: [ id ]
44 remote_location:
45 description:
46 - The remote location's name where the backup should be stored
47 type: str
48 remote_path:
49 description:
50 - This path is relative to the remote location.
51 - A '/' is automatically added between the remote location folder and this path.
52 - This folder structure should already exist on the remote location.
53 type: str
54 description:
55 description:
56 - Brief information about the backup.
57 type: str
58 destination:
59 description:
60 - Location where to download the backup to
61 type: str
62 state:
63 description:
64 - Use C(present) or C(absent) for adding or removing.
65 - Use C(query) for listing an object or multiple objects.
66 - Use C(upload) for uploading backup.
67 - Use C(restore) for restoring backup.
68 - Use C(download) for downloading backup.
69 - Use C(move) for moving backup from local to remote location.
70 type: str
71 choices: [ absent, present, query, upload, restore, download, move ]
72 default: present
73 extends_documentation_fragment: cisco.mso.modules
74 """
75
76 EXAMPLES = r"""
77 - name: Create a new local backup
78 cisco.mso.mso_backup:
79 host: mso_host
80 username: admin
81 password: SomeSecretPassword
82 backup: Backup
83 description: via Ansible
84 location_type: local
85 state: present
86
87 - name: Create a new remote backup
88 cisco.mso.mso_backup:
89 host: mso_host
90 username: admin
91 password: SomeSecretPassword
92 backup: Backup
93 description: via Ansible
94 location_type: remote
95 remote_location: ansible_test
96 state: present
97
98 - name: Move backup to remote location
99 cisco.mso.mso_backup:
100 host: mso_host
101 username: admin
102 password: SomeSecretPassword
103 backup: Backup0
104 remote_location: ansible_test
105 remote_path: test
106 state: move
107
108 - name: Download a backup
109 cisco.mso.mso_backup:
110 host: mso_host
111 username: admin
112 password: SomeSecretPassword
113 backup: Backup
114 destination: ./
115 state: download
116
117 - name: Upload a backup
118 cisco.mso.mso_backup:
119 host: mso_host
120 username: admin
121 password: SomeSecretPassword
122 backup: ./Backup
123 state: upload
124
125 - name: Restore a backup
126 cisco.mso.mso_backup:
127 host: mso_host
128 username: admin
129 password: SomeSecretPassword
130 backup: Backup
131 state: restore
132
133 - name: Remove a Backup
134 cisco.mso.mso_backup:
135 host: mso_host
136 username: admin
137 password: SomeSecretPassword
138 backup: Backup
139 state: absent
140
141 - name: Query a backup
142 cisco.mso.mso_backup:
143 host: mso_host
144 username: admin
145 password: SomeSecretPassword
146 backup: Backup
147 state: query
148 register: query_result
149
150 - name: Query a backup with its complete name
151 cisco.mso.mso_backup:
152 host: mso_host
153 username: admin
154 password: SomeSecretPassword
155 backup: Backup_20200721220043
156 state: query
157 register: query_result
158
159 - name: Query all backups
160 cisco.mso.mso_backup:
161 host: mso_host
162 username: admin
163 password: SomeSecretPassword
164 state: query
165 register: query_result
166 """
167
168 RETURN = r"""
169 """
170
171 from ansible.module_utils.basic import AnsibleModule
172 from ansible_collections.cisco.mso.plugins.module_utils.mso import MSOModule, mso_argument_spec
173 import os
174
175
176 def main():
177 argument_spec = mso_argument_spec()
178 argument_spec.update(
179 location_type=dict(type="str", default="local", choices=["local", "remote"]),
180 description=dict(type="str"),
181 backup=dict(type="str", aliases=["name"]),
182 backup_id=dict(type="str", aliases=["id"]),
183 remote_location=dict(type="str"),
184 remote_path=dict(type="str"),
185 state=dict(type="str", default="present", choices=["absent", "present", "query", "upload", "restore", "download", "move"]),
186 destination=dict(type="str"),
187 )
188
189 module = AnsibleModule(
190 argument_spec=argument_spec,
191 supports_check_mode=True,
192 required_if=[
193 ["location_type", "remote", ["remote_location"]],
194 ["state", "absent", ["backup", "backup_id"], True],
195 ["state", "present", ["backup"]],
196 ["state", "upload", ["backup", "backup_id"], True],
197 ["state", "restore", ["backup", "backup_id"], True],
198 ["state", "download", ["backup", "backup_id"], True],
199 ["state", "download", ["destination"]],
200 ["state", "move", ["backup", "backup_id"], True],
201 ["state", "move", ["remote_location", "remote_path"]],
202 ],
203 mutually_exclusive=[
204 ("backup", "backup_id"),
205 ],
206 )
207
208 description = module.params.get("description")
209 location_type = module.params.get("location_type")
210 state = module.params.get("state")
211 backup = module.params.get("backup")
212 backup_id = module.params.get("backup_id")
213 remote_location = module.params.get("remote_location")
214 remote_path = module.params.get("remote_path")
215 destination = module.params.get("destination")
216
217 mso = MSOModule(module)
218
219 backup_names = []
220 mso.existing = mso.query_objs("backups/backupRecords", key="backupRecords")
221 if backup or backup_id:
222 if mso.existing:
223 data = mso.existing
224 mso.existing = []
225 for backup_info in data:
226 if (backup_id and backup_id == backup_info.get("id")) or (
227 backup and (backup == backup_info.get("name").split("_")[0] or backup == backup_info.get("name"))
228 ):
229 mso.existing.append(backup_info)
230 backup_names.append(backup_info.get("name"))
231
232 if state == "query":
233 mso.exit_json()
234
235 elif state == "absent":
236 mso.previous = mso.existing
237 if len(mso.existing) > 1:
238 mso.module.fail_json(msg="Multiple backups with same name found. Existing backups with similar names: {0}".format(", ".join(backup_names)))
239 elif len(mso.existing) == 1:
240 if module.check_mode:
241 mso.existing = {}
242 else:
243 mso.existing = mso.request("backups/backupRecords/{id}".format(id=mso.existing[0].get("id")), method="DELETE")
244 mso.exit_json()
245
246 elif state == "present":
247 mso.previous = mso.existing
248
249 payload = dict(name=backup, description=description, locationType=location_type)
250
251 if location_type == "remote":
252 remote_location_info = mso.lookup_remote_location(remote_location)
253 payload.update(remoteLocationId=remote_location_info.get("id"))
254 if remote_path:
255 remote_path = "{0}/{1}".format(remote_location_info.get("path"), remote_path)
256 payload.update(remotePath=remote_path)
257
258 mso.proposed = payload
259
260 if module.check_mode:
261 mso.existing = mso.proposed
262 else:
263 mso.existing = mso.request("backups", method="POST", data=payload)
264 mso.exit_json()
265
266 elif state == "upload":
267 mso.previous = mso.existing
268
269 if module.check_mode:
270 mso.existing = mso.proposed
271 else:
272 try:
273 request_url = "backups/upload"
274 payload = dict()
275 if mso.platform == "nd":
276 if remote_location is None or remote_path is None:
277 mso.module.fail_json(msg="NDO backup upload failed: remote_location and remote_path are required for NDO backup upload")
278 remote_location_info = mso.lookup_remote_location(remote_location)
279 request_url = "backups/remoteUpload/{0}".format(remote_location_info.get("id"))
280 else:
281 payload = dict(name=(os.path.basename(backup), open(backup, "rb"), "application/x-gzip"))
282
283 mso.existing = mso.request_upload(request_url, fields=payload)
284 except Exception as error:
285 mso.module.fail_json(msg="Upload failed due to: {0}, Backup file: '{1}'".format(error, ", ".join(backup.split("/")[-1:])))
286 mso.exit_json()
287
288 if len(mso.existing) == 0:
289 mso.module.fail_json(msg="Backup '{0}' does not exist".format(backup))
290 elif len(mso.existing) > 1:
291 mso.module.fail_json(msg="Multiple backups with same name found. Existing backups with similar names: {0}".format(", ".join(backup_names)))
292
293 elif state == "restore":
294 mso.previous = mso.existing
295 if module.check_mode:
296 mso.existing = mso.proposed
297 else:
298 mso.existing = mso.request("backups/{id}/restore".format(id=mso.existing[0].get("id")), method="PUT")
299
300 elif state == "download":
301 mso.previous = mso.existing
302 if module.check_mode:
303 mso.existing = mso.proposed
304 else:
305 mso.existing = mso.request_download("backups/{id}/download".format(id=mso.existing[0].get("id")), destination=destination)
306
307 elif state == "move":
308 mso.previous = mso.existing
309 remote_location_info = mso.lookup_remote_location(remote_location)
310 remote_path = "{0}/{1}".format(remote_location_info.get("path"), remote_path)
311 payload = dict(remoteLocationId=remote_location_info.get("id"), remotePath=remote_path, backupRecordId=mso.existing[0].get("id"))
312 if module.check_mode:
313 mso.existing = mso.proposed
314 else:
315 mso.existing = mso.request("backups/remote-location", method="POST", data=payload)
316
317 mso.exit_json()
318
319
320 if __name__ == "__main__":
321 main()