Debian Codegraph @

ansible_collections/netapp/storagegrid/plugins/modules/na_sg_grid_ilm_policy.py

raw
1 #!/usr/bin/python
2
3 # (c) 2024, NetApp Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """NetApp StorageGRID - Manage ILM policies"""
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 ANSIBLE_METADATA = {
14 "metadata_version": "1.0",
15 "status": ["preview"],
16 "supported_by": "community",
17 }
18
19 DOCUMENTATION = """
20 module: na_sg_grid_ilm_policy
21 short_description: Manage ILM policies on StorageGRID.
22 extends_documentation_fragment:
23 - netapp.storagegrid.netapp.sg
24 version_added: '21.14.0'
25 author: Denis Magel (@dmagel-netapp) <[email protected]>
26 description:
27 - Interact with ILM policies on NetApp StorageGRID.
28 options:
29 default_rule:
30 description:
31 - The rule ID of the defailt rule in the policy.
32 - This tile ID must be included in rules
33 - If compliance is enabled, this must be the compliance-compatible rule
34 type: str
35 name:
36 description:
37 - The unique name of the policy
38 required: true
39 type: str
40 reason:
41 description:
42 - Policy description
43 required: false
44 type: str
45 rules:
46 description:
47 - A list of ILM rule IDs, in the order in which they will be evaluated
48 - This list must include the default rule
49 - If compliance is enabled, the default rule for objects in non-compliant buckets should be before the compliance-compatible default rule
50 type: list
51 elements: str
52 state:
53 description:
54 - Whether the specified policy should exist.
55 required: false
56 type: str
57 choices: ['present', 'absent']
58 default: present
59 validate_certs:
60 description:
61 - Should https certificates be validated?
62 required: false
63 type: bool
64 default: true
65 """
66
67 EXAMPLES = """
68 - name: Create ILM policy
69 na_sg_grid_ilm_policy:
70 api_url: "https://<storagegrid-endpoint-url>"
71 auth_token: "storagegrid-auth-token"
72 name: "1 Copy Per Site"
73 state: present
74 reason: "The 1 Copy Per Site policy placves 1 replicated copy at each site"
75 default_rule: r601033236249396421
76 rules:
77 - r601033236249396421
78
79 - name: Delete existing ILM policy
80 na_sg_grid_ilm_policy:
81 api_url: "https://<storagegrid-endpoint-url>"
82 auth_token: "storagegrid-auth-token"
83 name: "1 Copy Per Site"
84 state: absent
85 """
86
87 RETURN = """
88 resp:
89 description: Returns information about the StorageGRID ILM policy.
90 returned: If state is 'present'.
91 type: dict
92 sample: {
93 "activatedBy": [],
94 "active": false,
95 "defaultRule": "r601033236249396421",
96 "id": "f9cecfd8-fe93-4529-b883-d1707e753009",
97 "name": "1 Copy Per Site",
98 "reason": "The 1 Copy Per Site policy placves 1 replicated copy at each site",
99 "rules": [
100 "r601033236249396421"
101 ]
102 }
103 """
104
105 from datetime import datetime
106
107 import ansible_collections.netapp.storagegrid.plugins.module_utils.netapp as netapp_utils
108 from ansible.module_utils.basic import AnsibleModule
109 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp_module import NetAppModule
110 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp import SGRestAPI
111
112 __LOGGING__ = []
113
114
115 class ILM_policy(object):
116 """
117 Create, modify and delete StorageGRID ILM policy
118 """
119
120 def __init__(self):
121 """
122 Parse arguments, setup state variables,
123 check parameters and ensure request module is installed
124 """
125 self.argument_spec = netapp_utils.na_storagegrid_host_argument_spec()
126 self.argument_spec.update(
127 dict(
128 state=dict(required=False, type="str", choices=["present", "absent"], default="present"),
129 name=dict(required=True, type="str"),
130 default_rule=dict(required=False, type="str"),
131 reason=dict(required=False, type="str"),
132 rules=dict(required=False, type="list", elements="str"),
133 )
134 )
135 self.module = AnsibleModule(
136 argument_spec=self.argument_spec,
137 required_if=[("state", "present", ["default_rule", "rules"])],
138 supports_check_mode=True,
139 )
140 self.na_helper = NetAppModule()
141
142 # set up state variables
143 self.parameters = self.na_helper.set_parameters(self.module.params)
144 __LOGGING__.append("params: %s" % (self.module.params))
145 # Calling generic SG rest_api class
146 self.rest_api = SGRestAPI(self.module)
147 # Get API version
148 self.rest_api.get_sg_product_version()
149 self.api_version = self.rest_api.get_api_version()
150
151 # Create body for creation request (POST with state present)
152 self.data = {}
153 self.data["name"] = self.parameters["name"]
154 if self.parameters.get("rules"):
155 self.data["rules"] = self.parameters["rules"]
156 if self.parameters.get("default_rule"):
157 self.data["defaultRule"] = self.parameters["default_rule"]
158 # optional parameters
159 if self.parameters.get("reason"):
160 self.data["reason"] = self.parameters.get("reason")
161 __LOGGING__.append("data: %s" % (self.data))
162
163 def module_logging_handler(self, log_msg):
164 """Module logging handler"""
165 # Create timestamp for logs
166 date_now = datetime.now()
167 timestamp = date_now.strftime("%Y/%m/%d-%H:%M:%S")
168 # Log events
169 self.module.log(log_msg)
170 __LOGGING__.append("%s: %s" % (timestamp, log_msg))
171
172 def get_ilm_policy(self):
173 # Check if policy exists
174 # Return info if found, or None
175 api = "api/%s/grid/ilm-policies" % self.api_version
176 response, error = self.rest_api.get(api)
177
178 if error:
179 self.module.fail_json(msg=error, log=__LOGGING__)
180 self.module_logging_handler("all ILM policies: %s" % (response['data']))
181 # if policy with 'name' exists, return it, else none
182 for policy in response["data"]:
183 if policy["name"] == self.parameters["name"]:
184 self.id = policy["id"]
185 return policy
186
187 return None
188
189 def create_ilm_policy(self):
190 __LOGGING__.append("creating ILM policy with payload: %s" % (self.data))
191 api = "api/%s/grid/ilm-policies" % self.api_version
192 response, error = self.rest_api.post(api, self.data)
193
194 if error:
195 self.module.fail_json(msg=error, log=__LOGGING__)
196
197 return response["data"]
198
199 def delete_ilm_policy(self):
200 __LOGGING__.append("deleting ILM policy")
201 api = "api/%s/grid/ilm-policies/%s" % (self.api_version, self.id)
202
203 response, error = self.rest_api.delete(api, None)
204 if error:
205 self.module.fail_json(msg=error, log=__LOGGING__)
206
207 def update_ilm_policy(self):
208 __LOGGING__.append("updating ILM policy with payload: %s" % self.data)
209 api = "api/%s/grid/ilm-policies/%s" % (self.api_version, self.id)
210 response, error = self.rest_api.put(api, self.data)
211
212 if error:
213 self.module.fail_json(msg=error, log=__LOGGING__)
214
215 return response["data"]
216
217 def apply(self):
218 """
219 Perform pre-checks, call functions and exit
220 """
221
222 ilm_policy = self.get_ilm_policy()
223 self.module_logging_handler("got matching ILM policys: %s" % ilm_policy)
224
225 cd_action = self.na_helper.get_cd_action(ilm_policy, self.parameters)
226
227 if cd_action is None and self.parameters["state"] == "present":
228 # let's see if we need to update parameters
229 if self.data.get("reason") and self.data.get("reason") != ilm_policy.get("reason"):
230 self.na_helper.changed = True
231 if self.data.get("rules") and self.data.get("rules") != ilm_policy.get("rules"):
232 self.na_helper.changed = True
233 if self.data.get("default_rule") and self.data.get("default_rule") != ilm_policy.get("defaultRule"):
234 self.na_helper.changed = True
235
236 result_message = ""
237 resp_data = ilm_policy
238 if self.na_helper.changed:
239 if self.module.check_mode:
240 pass
241 else:
242 if cd_action == "delete":
243 self.delete_ilm_policy()
244 resp_data = None
245 result_message = "ILM policy deleted"
246 __LOGGING__.append("ILM policy deleted")
247
248 elif cd_action == "create":
249 resp_data = self.create_ilm_policy()
250 result_message = "ILM policy created"
251 __LOGGING__.append("ILM policy created")
252
253 else:
254 resp_data = self.update_ilm_policy()
255 result_message = "ILM policy updated"
256 __LOGGING__.append("ILM policy updated")
257
258 self.module.exit_json(changed=self.na_helper.changed, msg=result_message, resp=resp_data, log=__LOGGING__)
259
260
261 def main():
262 """
263 Main function
264 """
265 na_sg_ilm_policy = ILM_policy()
266 na_sg_ilm_policy.apply()
267
268
269 if __name__ == "__main__":
270 main()