Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2020, Shreyas Srish (@shrsr) <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}
12
13 DOCUMENTATION = r"""
14 ---
15 module: mso_backup_schedule
16 short_description: Manages backup schedules
17 description:
18 - Manage backup schedules on Cisco ACI Multi-Site.
19 author:
20 - Akini Ross (@akinross)
21 options:
22 start_date:
23 description:
24 - The date to start the scheduler in format YYYY-MM-DD
25 - If no date is provided, the current date will be used.
26 type: str
27 start_time:
28 description:
29 - The time to start the scheduler in format HH:MM:SS
30 - If no time is provided, midnight "00:00:00" will be used.
31 type: str
32 frequency_unit:
33 description:
34 - The interval unit type
35 choices: [ hours, days ]
36 type: str
37 frequency_length:
38 description:
39 - Amount of hours or days for the schedule trigger frequency
40 type: int
41 remote_location:
42 description:
43 - The remote location's name where the backup should be stored
44 type: str
45 remote_path:
46 description:
47 - This path is relative to the remote location.
48 - A '/' is automatically added between the remote location folder and this path.
49 - This folder structure should already exist on the remote location.
50 type: str
51 state:
52 description:
53 - Use C(present) or C(absent) for adding or removing.
54 - Use C(query) for listing an object or multiple objects.
55 type: str
56 choices: [ absent, present, query ]
57 default: present
58 extends_documentation_fragment: cisco.mso.modules
59 """
60
61 EXAMPLES = r"""
62 - name: Get current backup schedule
63 cisco.mso.mso_backup_schedule:
64 host: mso_host
65 username: admin
66 password: SomeSecretPassword
67 state: query
68 register: query_result
69
70 - name: Set backup schedule
71 cisco.mso.mso_backup_schedule:
72 host: mso_host
73 username: admin
74 password: SomeSecretPassword
75 frequency_unit: hours
76 frequency_length: 7
77 remote_location: ansible_test
78 state: present
79
80 - name: Set backup schedule with date and time
81 cisco.mso.mso_backup_schedule:
82 host: mso_host
83 username: admin
84 password: SomeSecretPassword
85 frequency_unit: days
86 frequency_length: 1
87 remote_location: ansible_test
88 remote_path: test
89 start_time: 20:57:36
90 start_date: 2023-04-09
91 state: present
92
93 - name: Delete backup schedule
94 cisco.mso.mso_backup_schedule:
95 host: mso_host
96 username: admin
97 password: SomeSecretPassword
98 state: absent
99 """
100
101 RETURN = r"""
102 """
103
104 from ansible.module_utils.basic import AnsibleModule
105 from ansible_collections.cisco.mso.plugins.module_utils.mso import MSOModule, mso_argument_spec
106 from datetime import datetime, tzinfo, timedelta
107
108 # UTC Timezone implementation as datetime.timezone is not supported in Python 2.7
109
110
111 class UTC(tzinfo):
112 """UTC"""
113
114 def utcoffset(self, dt):
115 return timedelta(0)
116
117 def tzname(self, dt):
118 return "UTC"
119
120 def dst(self, dt):
121 return timedelta(0)
122
123
124 def main():
125 argument_spec = mso_argument_spec()
126 argument_spec.update(
127 start_date=dict(type="str"),
128 start_time=dict(type="str"),
129 frequency_unit=dict(type="str", choices=["hours", "days"]),
130 frequency_length=dict(type="int"),
131 remote_location=dict(type="str"),
132 remote_path=dict(type="str"),
133 state=dict(type="str", default="present", choices=["absent", "present", "query"]),
134 )
135
136 module = AnsibleModule(
137 argument_spec=argument_spec, supports_check_mode=True, required_if=[["state", "present", ["frequency_unit", "frequency_length", "remote_location"]]]
138 )
139
140 start_date = module.params.get("start_date")
141 start_time = module.params.get("start_time")
142 frequency_unit = module.params.get("frequency_unit")
143 frequency_length = module.params.get("frequency_length")
144 remote_location = module.params.get("remote_location")
145 remote_path = module.params.get("remote_path")
146 state = module.params.get("state")
147
148 mso = MSOModule(module)
149 api_path = "backups/schedule"
150 mso.existing = mso.request(api_path, method="GET")
151
152 if state == "absent":
153 mso.previous = mso.existing
154 if module.check_mode:
155 mso.existing = {}
156 else:
157 mso.existing = mso.request(api_path, method="DELETE")
158
159 elif state == "present":
160 mso.previous = mso.existing
161
162 remote_location_info = mso.lookup_remote_location(remote_location)
163
164 if start_date:
165 try:
166 y, m, d = start_date.split("-")
167 year = int(y)
168 month = int(m)
169 day = int(d)
170 except Exception as e:
171 module.fail_json(msg="Failed to parse date format 'YYYY-MM-DD' %s, %s" % (start_date, e))
172 else:
173 current_date = datetime.now(UTC()).date()
174 year = current_date.year
175 month = current_date.month
176 day = current_date.day
177
178 if start_time:
179 try:
180 h, m, s = start_time.split(":")
181 hours = int(h)
182 minutes = int(m)
183 seconds = int(s)
184 except Exception as e:
185 module.fail_json(msg="Failed to parse time format 'HH:MM:SS' %s, %s" % (start_time, e))
186 else:
187 hours = minutes = seconds = 0
188
189 try:
190 set_date = datetime(year, month, day, hours, minutes, seconds)
191 except Exception as e:
192 module.fail_json(msg="Failed to create datetime object with date '%s', and time '%s'. Error: %s" % (start_date, start_time, e))
193
194 payload = dict(
195 startDate="{0}.000Z".format(set_date.isoformat()),
196 intervalTimeUnit=frequency_unit.upper(),
197 intervalLength=frequency_length,
198 remoteLocationId=remote_location_info.get("id"),
199 locationType="remote",
200 )
201
202 if remote_path:
203 payload.update(remotePath="{0}/{1}".format(remote_location_info.get("path"), remote_path))
204
205 mso.proposed = payload
206
207 if module.check_mode:
208 mso.existing = mso.proposed
209 else:
210 mso.existing = mso.request(api_path, method="POST", data=payload)
211
212 mso.exit_json()
213
214
215 if __name__ == "__main__":
216 main()