Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_publickey.py

raw
1 #!/usr/bin/python
2
3 # (c) 2021-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 '''
7 na_ontap_publickey
8 '''
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14
15 module: na_ontap_publickey
16
17 short_description: NetApp ONTAP publickey configuration
18 extends_documentation_fragment:
19 - netapp.ontap.netapp.na_ontap_rest
20 version_added: 21.7.0
21 author: NetApp Ansible Team (@carchi8py) <[email protected]>
22
23 description:
24 - Add, modify, or remove publickeys.
25 - Requires ONTAP 9.7 or later, and only supports REST.
26
27 options:
28 state:
29 description:
30 - Whether the specified publickey should exist or not.
31 choices: ['present', 'absent']
32 type: str
33 default: 'present'
34 account:
35 description:
36 - The name of the user account.
37 required: true
38 type: str
39 comment:
40 description:
41 - Optional comment for the public key.
42 type: str
43 delete_all:
44 description:
45 - If index is not present, with state=absent, delete all public key for this user account.
46 type: bool
47 default: false
48 index:
49 description:
50 - Index number for the public key.
51 - If index is not present, with state=present, the public key is always added, using the next available index.
52 - If index is not present, with state=present, the module is not idempotent.
53 - If index is not present, with state=absent, if only one key is found, it is deleted. Otherwise an error is reported.
54 - See also C(delete_all) option.
55 type: int
56 public_key:
57 description:
58 - The public key.
59 type: str
60 vserver:
61 description:
62 - The name of the vserver to use.
63 - Omit this option for cluster scoped user accounts.
64 type: str
65
66 notes:
67 - This module supports check_mode.
68 - This module is not idempotent if index is omitted.
69 '''
70
71 EXAMPLES = """
72 - name: Create publickey
73 netapp.ontap.na_ontap_publickey:
74 state: present
75 account: SampleUser
76 index: 0
77 public_key: "{{ netapp_publickey }}"
78 vserver: ansibleVServer
79 hostname: "{{ netapp_hostname }}"
80 username: "{{ netapp_username }}"
81 password: "{{ netapp_password }}"
82
83 - name: Delete single publickey
84 netapp.ontap.na_ontap_publickey:
85 state: absent
86 account: SampleUser
87 vserver: ansibleVServer
88 hostname: "{{ netapp_hostname }}"
89 username: "{{ netapp_username }}"
90 password: "{{ netapp_password }}"
91
92 - name: Modify single publickey
93 netapp.ontap.na_ontap_publickey:
94 state: present
95 account: SampleUser
96 comment: ssh key for XXXX
97 index: 0
98 vserver: ansibleVServer
99 hostname: "{{ netapp_hostname }}"
100 username: "{{ netapp_username }}"
101 password: "{{ netapp_password }}"
102 """
103
104 RETURN = """
105 cd_action:
106 description: whether a public key is created or deleted.
107 returned: success
108 type: str
109
110 modify:
111 description: attributes that were modified if the key already exists.
112 returned: success
113 type: dict
114 """
115
116 from ansible.module_utils.basic import AnsibleModule
117 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
118 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
119 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
120 import ansible_collections.netapp.ontap.plugins.module_utils.rest_response_helpers as rrh
121
122 HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
123
124
125 class NetAppOntapPublicKey:
126 """
127 Common operations to manage public keys.
128 """
129
130 def __init__(self):
131 self.use_rest = False
132 argument_spec = netapp_utils.na_ontap_rest_only_spec()
133 argument_spec.update(dict(
134 state=dict(type='str', choices=['present', 'absent'], default='present'),
135 account=dict(required=True, type='str'),
136 comment=dict(type='str'),
137 delete_all=dict(type='bool', default=False),
138 index=dict(type='int'),
139 public_key=dict(type='str'),
140 vserver=dict(type='str'),
141 ))
142
143 self.module = AnsibleModule(
144 argument_spec=argument_spec,
145 mutually_exclusive=[
146 ('delete_all', 'index')
147 ],
148 supports_check_mode=True
149 )
150
151 self.na_helper = NetAppModule()
152 self.parameters = self.na_helper.set_parameters(self.module.params)
153
154 # REST API is required
155 self.rest_api = OntapRestAPI(self.module)
156 # check version
157 self.rest_api.fail_if_not_rest_minimum_version('na_ontap_publickey', 9, 7)
158
159 def get_public_keys(self):
160 api = 'security/authentication/publickeys'
161 query = {
162 'account.name': self.parameters['account'],
163 'fields': 'account,owner,index,public_key,comment'
164 }
165 if self.parameters.get('vserver') is None:
166 # vserser is empty for cluster
167 query['scope'] = 'cluster'
168 else:
169 query['owner.name'] = self.parameters['vserver']
170
171 if self.parameters.get('index') is not None:
172 query['index'] = self.parameters['index']
173
174 response, error = self.rest_api.get(api, query)
175 if self.parameters.get('index') is not None:
176 record, error = rrh.check_for_0_or_1_records(api, response, error)
177 records = [record]
178 else:
179 records, error = rrh.check_for_0_or_more_records(api, response, error)
180 if error:
181 msg = "Error in get_public_key: %s" % error
182 self.module.fail_json(msg=msg)
183 if records is None or records == [None]:
184 records = []
185 # flatten {'account': {'name': 'some_name'}} into {'account': 'some_name'} to match input parameters
186 return [dict([(k, v if k != 'account' else v['name']) for k, v in record.items()]) for record in records]
187
188 def create_public_key(self):
189 api = 'security/authentication/publickeys'
190 body = {
191 'account.name': self.parameters['account'],
192 'public_key': self.parameters['public_key']
193 }
194 if self.parameters.get('vserver') is not None:
195 # vserser is empty for cluster
196 body['owner.name'] = self.parameters['vserver']
197 for attr in ('comment', 'index'):
198 value = self.parameters.get(attr)
199 if value is not None:
200 body[attr] = value
201
202 dummy, error = self.rest_api.post(api, body)
203 if error:
204 msg = "Error in create_public_key: %s" % error
205 self.module.fail_json(msg=msg)
206
207 def modify_public_key(self, current, modify):
208 # not supported in 2.6
209 # sourcery skip: dict-comprehension
210 api = 'security/authentication/publickeys/%s/%s/%d' % (current['owner']['uuid'], current['account'], current['index'])
211 body = {}
212 modify_copy = dict(modify)
213 for key in modify:
214 if key in ('comment', 'public_key'):
215 body[key] = modify_copy.pop(key)
216 if modify_copy:
217 msg = 'Error: attributes not supported in modify: %s' % modify_copy
218 self.module.fail_json(msg=msg)
219 if not body:
220 msg = 'Error: nothing to change - modify called with: %s' % modify
221 self.module.fail_json(msg=msg)
222 if 'public_key' not in body:
223 # if not present, REST API reports 502 Server Error: Proxy Error for url
224 body['public_key'] = current['public_key']
225
226 dummy, error = self.rest_api.patch(api, body)
227 if error:
228 msg = "Error in modify_public_key: %s" % error
229 self.module.fail_json(msg=msg)
230
231 def delete_public_key(self, current):
232 api = 'security/authentication/publickeys/%s/%s/%d' % (current['owner']['uuid'], current['account'], current['index'])
233 dummy, error = self.rest_api.delete(api)
234 if error:
235 msg = "Error in delete_public_key: %s" % error
236 self.module.fail_json(msg=msg)
237
238 def get_actions(self):
239 """Determines whether a create, delete, modify action is required
240 If index is provided, we expect to find 0 or 1 record.
241 If index is not provided:
242 1. As documented in ONTAP, a create without index should add a new public key.
243 This is not idempotent, and this rules out a modify operation.
244 2. When state is absent, if a single record is found, we assume a delete.
245 3. When state is absent, if more than one record is found, a delete action is rejected with 1 exception:
246 we added a delete_all option, so that all existing keys can be deleted.
247 """
248 cd_action, current, modify = None, None, None
249 if self.parameters['state'] == 'present' and self.parameters.get('index') is None:
250 # always create, by keeping current as None
251 self.module.warn('Module is not idempotent if index is not provided with state=present.')
252 records = []
253 else:
254 records = self.get_public_keys()
255 if len(records) > 1:
256 if self.parameters['state'] == 'absent' and self.parameters.get('delete_all'):
257 cd_action = 'delete_all'
258 self.na_helper.changed = True
259 else:
260 msg = 'index is required as more than one public_key exists for user account %s: ' % self.parameters['account']
261 msg += str(records)
262 self.module.fail_json(msg='Error: %s' % msg)
263 elif len(records) == 1:
264 current = records[0]
265
266 if cd_action is None:
267 cd_action = self.na_helper.get_cd_action(current, self.parameters)
268 if cd_action is None:
269 if current and 'comment' not in current:
270 # force an entry as REST does not return anything if no comment was set
271 current['comment'] = ''
272 modify = self.na_helper.get_modified_attributes(current, self.parameters)
273
274 return cd_action, modify, records
275
276 def apply(self):
277 cd_action, modify, records = self.get_actions()
278
279 if self.na_helper.changed and not self.module.check_mode:
280 if cd_action == 'create':
281 self.create_public_key()
282 elif cd_action in ('delete', 'delete_all'):
283 # there is exactly 1 record for delete
284 # and 2 or more records for delete_all
285 for record in records:
286 self.delete_public_key(record)
287 elif modify:
288 # there is exactly 1 record for modify
289 self.modify_public_key(records[0], modify)
290
291 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
292 self.module.exit_json(**result)
293
294
295 def main():
296 obj = NetAppOntapPublicKey()
297 obj.apply()
298
299
300 if __name__ == '__main__':
301 main()