Debian Codegraph @

ansible_collections/community/hrobot/plugins/modules/ssh_key.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2019 Felix Fontein <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r"""
13 module: ssh_key
14 short_description: Add, remove or update SSH key
15 version_added: 1.2.0
16 author:
17 - Felix Fontein (@felixfontein)
18 description:
19 - Add, remove or update an SSH key stored in Hetzner's Robot.
20 seealso:
21 - module: community.hrobot.ssh_key_info
22 description: Query information on SSH keys.
23 extends_documentation_fragment:
24 - community.hrobot.robot
25 - community.hrobot.attributes
26 - community.hrobot.attributes.actiongroup_robot
27
28 attributes:
29 action_group:
30 version_added: 1.6.0
31 check_mode:
32 support: full
33 diff_mode:
34 support: none
35 idempotent:
36 support: full
37
38 options:
39 state:
40 description:
41 - Whether to make sure a public SSH key is present or absent.
42 - V(present) makes sure that the SSH key is available, and potentially updates names for existing SSH public keys.
43 - V(absent) makes sure that the SSH key is not available. The fingerprint or public key data is used for matching the
44 key.
45 required: true
46 type: str
47 choices:
48 - present
49 - absent
50 name:
51 description:
52 - The public key's name.
53 - Required if O(state=present), and ignored if O(state=absent).
54 type: str
55 fingerprint:
56 description:
57 - The MD5 fingerprint of the public SSH key to remove.
58 - One of O(public_key) and O(fingerprint) are required if O(state=absent).
59 type: str
60 public_key:
61 description:
62 - The public key data in OpenSSH format.
63 - 'Example: V(ssh-rsa AAAAB3NzaC1yc+..).'
64 - One of O(public_key) and O(fingerprint) are required if O(state=absent).
65 - Required if O(state=present).
66 type: str
67 """
68
69 EXAMPLES = r"""
70 ---
71 - name: Add an SSH key
72 community.hrobot.ssh_key:
73 hetzner_user: foo
74 hetzner_password: bar
75 state: present
76 name: newKey
77 public_key: ssh-rsa AAAAB3NzaC1yc+...
78
79 - name: Remove a SSH key by fingerprint
80 community.hrobot.ssh_key:
81 hetzner_user: foo
82 hetzner_password: bar
83 state: absent
84 fingerprint: cb:8b:ef:a7:fe:04:87:3f:e5:55:cd:12:e3:e8:9f:99
85 """
86
87 RETURN = r"""
88 fingerprint:
89 description:
90 - The MD5 fingerprint of the key.
91 - This is the value used to reference the SSH public key, for example in the M(community.hrobot.boot) module.
92 returned: success
93 type: str
94 sample: cb:8b:ef:a7:fe:04:87:3f:e5:55:cd:12:e3:e8:9f:99
95 """
96
97 from ansible.module_utils.basic import AnsibleModule
98 from ansible.module_utils.common.text.converters import to_native
99
100 from ansible_collections.community.hrobot.plugins.module_utils.robot import (
101 BASE_URL,
102 ROBOT_DEFAULT_ARGUMENT_SPEC,
103 fetch_url_json,
104 )
105
106 from ansible_collections.community.hrobot.plugins.module_utils.ssh import (
107 FingerprintError,
108 normalize_fingerprint,
109 extract_fingerprint,
110 remove_comment,
111 )
112
113 try:
114 from urllib.parse import urlencode
115 except ImportError:
116 # Python 2.x fallback:
117 from urllib import urlencode
118
119
120 def main():
121 argument_spec = dict(
122 state=dict(type='str', required=True, choices=['present', 'absent']),
123 name=dict(type='str'),
124 fingerprint=dict(type='str'),
125 public_key=dict(type='str'),
126 )
127 argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC)
128 module = AnsibleModule(
129 argument_spec=argument_spec,
130 supports_check_mode=True,
131 mutually_exclusive=[
132 ('fingerprint', 'public_key'),
133 ],
134 required_if=[
135 ('state', 'present', ['name', 'public_key']),
136 ('state', 'absent', ['fingerprint', 'public_key'], True),
137 ],
138 )
139
140 state = module.params['state']
141 name = module.params['name']
142 fingerprint = module.params['fingerprint']
143 public_key = module.params['public_key']
144
145 try:
146 if fingerprint is not None:
147 fingerprint = normalize_fingerprint(fingerprint)
148 else:
149 fingerprint = extract_fingerprint(public_key)
150 except FingerprintError as exc:
151 module.fail_json(msg=to_native(exc))
152
153 url = "{0}/key/{1}".format(BASE_URL, fingerprint)
154
155 # Remove key
156 if state == 'absent':
157 if module.check_mode:
158 dummy, error = fetch_url_json(module, url, accept_errors=['NOT_FOUND'])
159 else:
160 dummy, error = fetch_url_json(module, url, accept_errors=['NOT_FOUND'], method='DELETE', allow_empty_result=True)
161 if error == 'NOT_FOUND':
162 changed = False
163 elif error is not None:
164 raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover
165 else:
166 changed = True
167 module.exit_json(changed=changed, fingerprint=fingerprint)
168
169 # Make sure key is present
170 result, error = fetch_url_json(module, url, accept_errors=['NOT_FOUND'])
171 if error == 'NOT_FOUND':
172 changed = True
173 exists = False
174 elif error is not None:
175 raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover
176 else:
177 exists = True
178 changed = False
179 # The only thing we can update is the name
180 if result['key'].get('name') != name:
181 changed = True
182
183 if changed and not module.check_mode:
184 data = {
185 'name': name,
186 }
187 if not exists:
188 # Create key
189 data['data'] = remove_comment(public_key)
190 url = "{0}/key".format(BASE_URL)
191 # Update or create key
192 headers = {"Content-type": "application/x-www-form-urlencoded"}
193 result, dummy = fetch_url_json(
194 module,
195 url,
196 data=urlencode(data),
197 headers=headers,
198 method='POST',
199 )
200
201 module.exit_json(changed=changed, fingerprint=fingerprint)
202
203
204 if __name__ == '__main__': # pragma: no cover
205 main() # pragma: no cover