Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/netapp_e_snapshot_images.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # (c) 2016, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9
10 ANSIBLE_METADATA = {'metadata_version': '1.1',
11 'status': ['deprecated'],
12 'supported_by': 'community'}
13
14
15 DOCUMENTATION = """
16 ---
17 module: netapp_e_snapshot_images
18 short_description: NetApp E-Series create and delete snapshot images
19 description:
20 - Create and delete snapshots images on snapshot groups for NetApp E-series storage arrays.
21 - Only the oldest snapshot image can be deleted so consistency is preserved.
22 - "Related: Snapshot volumes are created from snapshot images."
23 version_added: '2.2.0'
24 author: Kevin Hulquest (@hulquest)
25 options:
26 ssid:
27 description:
28 - Storage system identifier
29 type: str
30 required: true
31 api_username:
32 required: true
33 description:
34 - The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.
35 type: str
36 api_password:
37 required: true
38 description:
39 - The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.
40 type: str
41 api_url:
42 required: true
43 description:
44 - The url to the SANtricity WebServices Proxy or embedded REST API.
45 type: str
46 validate_certs:
47 required: false
48 default: true
49 description:
50 - Should https certificates be validated?
51 type: bool
52 snapshot_group:
53 description:
54 - The name of the snapshot group in which you want to create a snapshot image.
55 required: True
56 type: str
57 state:
58 description:
59 - Whether a new snapshot image should be created or oldest be deleted.
60 required: True
61 type: str
62 choices: ['create', 'remove']
63 """
64 EXAMPLES = """
65 - name: Create Snapshot
66 netapp_e_snapshot_images:
67 ssid: "{{ ssid }}"
68 api_url: "{{ netapp_api_url }}"
69 api_username: "{{ netapp_api_username }}"
70 api_password: "{{ netapp_api_password }}"
71 validate_certs: "{{ validate_certs }}"
72 snapshot_group: "3300000060080E5000299C24000005B656D9F394"
73 state: 'create'
74 """
75 RETURN = """
76 ---
77 msg:
78 description: State of operation
79 type: str
80 returned: always
81 sample: "Created snapshot image"
82 image_id:
83 description: ID of snapshot image
84 type: str
85 returned: state == created
86 sample: "3400000060080E5000299B640063074057BC5C5E "
87 """
88
89 HEADERS = {
90 "Content-Type": "application/json",
91 "Accept": "application/json",
92 }
93 import json
94
95 from ansible.module_utils.api import basic_auth_argument_spec
96 from ansible.module_utils.basic import AnsibleModule
97
98 from ansible.module_utils._text import to_native
99 from ansible.module_utils.urls import open_url
100 from ansible.module_utils.six.moves.urllib.error import HTTPError
101
102
103 def request(url, data=None, headers=None, method='GET', use_proxy=True,
104 force=False, last_mod_time=None, timeout=10, validate_certs=True,
105 url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False):
106 try:
107 r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy,
108 force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
109 url_username=url_username, url_password=url_password, http_agent=http_agent,
110 force_basic_auth=force_basic_auth)
111 except HTTPError as err:
112 r = err.fp
113
114 try:
115 raw_data = r.read()
116 if raw_data:
117 data = json.loads(raw_data)
118 else:
119 raw_data = None
120 except Exception:
121 if ignore_errors:
122 pass
123 else:
124 raise Exception(raw_data)
125
126 resp_code = r.getcode()
127
128 if resp_code >= 400 and not ignore_errors:
129 raise Exception(resp_code, data)
130 else:
131 return resp_code, data
132
133
134 def snapshot_group_from_name(module, ssid, api_url, api_pwd, api_usr, name):
135 snap_groups = 'storage-systems/%s/snapshot-groups' % ssid
136 snap_groups_url = api_url + snap_groups
137 (ret, snapshot_groups) = request(snap_groups_url, url_username=api_usr, url_password=api_pwd, headers=HEADERS,
138 validate_certs=module.params['validate_certs'])
139
140 snapshot_group_id = None
141 for snapshot_group in snapshot_groups:
142 if name == snapshot_group['label']:
143 snapshot_group_id = snapshot_group['pitGroupRef']
144 break
145 if snapshot_group_id is None:
146 module.fail_json(msg="Failed to lookup snapshot group. Group [%s]. Id [%s]." % (name, ssid))
147
148 return snapshot_group
149
150
151 def oldest_image(module, ssid, api_url, api_pwd, api_usr, name):
152 get_status = 'storage-systems/%s/snapshot-images' % ssid
153 url = api_url + get_status
154
155 try:
156 (ret, images) = request(url, url_username=api_usr, url_password=api_pwd, headers=HEADERS,
157 validate_certs=module.params['validate_certs'])
158 except Exception as err:
159 module.fail_json(msg="Failed to get snapshot images for group. Group [%s]. Id [%s]. Error [%s]" %
160 (name, ssid, to_native(err)))
161 if not images:
162 module.exit_json(msg="There are no snapshot images to remove. Group [%s]. Id [%s]." % (name, ssid))
163
164 oldest = min(images, key=lambda x: x['pitSequenceNumber'])
165 if oldest is None or "pitRef" not in oldest:
166 module.fail_json(msg="Failed to lookup oldest snapshot group. Group [%s]. Id [%s]." % (name, ssid))
167
168 return oldest
169
170
171 def create_image(module, ssid, api_url, pwd, user, p, snapshot_group):
172 snapshot_group_obj = snapshot_group_from_name(module, ssid, api_url, pwd, user, snapshot_group)
173 snapshot_group_id = snapshot_group_obj['pitGroupRef']
174 endpoint = 'storage-systems/%s/snapshot-images' % ssid
175 url = api_url + endpoint
176 post_data = json.dumps({'groupId': snapshot_group_id})
177
178 image_data = request(url, data=post_data, method='POST', url_username=user, url_password=pwd, headers=HEADERS,
179 validate_certs=module.params['validate_certs'])
180
181 if image_data[1]['status'] == 'optimal':
182 status = True
183 id = image_data[1]['id']
184 else:
185 status = False
186 id = ''
187
188 return status, id
189
190
191 def delete_image(module, ssid, api_url, pwd, user, snapshot_group):
192 image = oldest_image(module, ssid, api_url, pwd, user, snapshot_group)
193 image_id = image['pitRef']
194 endpoint = 'storage-systems/%s/snapshot-images/%s' % (ssid, image_id)
195 url = api_url + endpoint
196
197 try:
198 (ret, image_data) = request(url, method='DELETE', url_username=user, url_password=pwd, headers=HEADERS,
199 validate_certs=module.params['validate_certs'])
200 except Exception as e:
201 image_data = (e[0], e[1])
202
203 if ret == 204:
204 deleted_status = True
205 error_message = ''
206 else:
207 deleted_status = False
208 error_message = image_data[1]['errorMessage']
209
210 return deleted_status, error_message
211
212
213 def main():
214 argument_spec = basic_auth_argument_spec()
215 argument_spec.update(dict(
216 snapshot_group=dict(required=True, type='str'),
217 ssid=dict(required=True, type='str'),
218 api_url=dict(required=True),
219 api_username=dict(type='str', required=True),
220 api_password=dict(type='str', required=True, no_log=True),
221 validate_certs=dict(required=False, type='bool', default=True),
222 state=dict(required=True, choices=['create', 'remove'], type='str'),
223 ))
224 module = AnsibleModule(argument_spec)
225
226 p = module.params
227
228 ssid = p.pop('ssid')
229 api_url = p.pop('api_url')
230 user = p.pop('api_username')
231 pwd = p.pop('api_password')
232 snapshot_group = p.pop('snapshot_group')
233 desired_state = p.pop('state')
234
235 if not api_url.endswith('/'):
236 api_url += '/'
237
238 if desired_state == 'create':
239 created_status, snapshot_id = create_image(module, ssid, api_url, pwd, user, p, snapshot_group)
240
241 if created_status:
242 module.exit_json(changed=True, msg='Created snapshot image', image_id=snapshot_id)
243 else:
244 module.fail_json(
245 msg="Could not create snapshot image on system %s, in snapshot group %s" % (ssid, snapshot_group))
246 else:
247 deleted, error_msg = delete_image(module, ssid, api_url, pwd, user, snapshot_group)
248
249 if deleted:
250 module.exit_json(changed=True, msg='Deleted snapshot image for snapshot group [%s]' % (snapshot_group))
251 else:
252 module.fail_json(
253 msg="Could not create snapshot image on system %s, in snapshot group %s --- %s" % (
254 ssid, snapshot_group, error_msg))
255
256
257 if __name__ == '__main__':
258 main()