Debian Codegraph @

ansible_collections/community/general/plugins/modules/ssh_config.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2015, Björn Andersson
4 # Copyright (c) 2021, Ansible Project
5 # Copyright (c) 2021, Abhijeet Kasurde <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: ssh_config
13 short_description: Manage SSH config for user
14 version_added: '2.0.0'
15 description:
16 - Configures SSH hosts with special C(IdentityFile)s and hostnames.
17 author:
18 - Björn Andersson (@gaqzi)
19 - Abhijeet Kasurde (@Akasurde)
20 extends_documentation_fragment:
21 - community.general._attributes
22 attributes:
23 check_mode:
24 support: full
25 diff_mode:
26 support: none
27 options:
28 state:
29 description:
30 - Whether a host entry should exist or not.
31 default: present
32 choices: ['present', 'absent']
33 type: str
34 user:
35 description:
36 - Which user account this configuration file belongs to.
37 - If none given and O(ssh_config_file) is not specified, C(/etc/ssh/ssh_config) is used.
38 - If a user is given, C(~/.ssh/config) is used.
39 - Mutually exclusive with O(ssh_config_file).
40 type: str
41 group:
42 description:
43 - Which group this configuration file belongs to.
44 - If none given, O(user) is used.
45 type: str
46 host:
47 description:
48 - The endpoint this configuration is valid for.
49 - It can be an actual address on the internet or an alias that connects to the value of O(hostname).
50 required: true
51 type: str
52 hostname:
53 description:
54 - The actual host to connect to when connecting to the host defined.
55 type: str
56 port:
57 description:
58 - The actual port to connect to when connecting to the host defined.
59 type: str
60 remote_user:
61 description:
62 - Specifies the user to log in as.
63 type: str
64 identity_file:
65 description:
66 - The path to an identity file (SSH private key) that is used when connecting to this host.
67 - File need to exist and have mode V(0600) to be valid.
68 type: path
69 identities_only:
70 description:
71 - Specifies that SSH should only use the configured authentication identity and certificate files (either the default
72 files, or those explicitly configured in the C(ssh_config) files or passed on the ssh command-line), even if C(ssh-agent)
73 or a C(PKCS11Provider) or C(SecurityKeyProvider) offers more identities.
74 type: bool
75 version_added: 8.2.0
76 user_known_hosts_file:
77 description:
78 - Sets the user known hosts file option.
79 type: str
80 strict_host_key_checking:
81 description:
82 - Whether to strictly check the host key when doing connections to the remote host.
83 - The value V(accept-new) is supported since community.general 8.6.0.
84 choices: ['yes', 'no', 'ask', 'accept-new']
85 type: str
86 proxycommand:
87 description:
88 - Sets the C(ProxyCommand) option.
89 - Mutually exclusive with O(proxyjump).
90 type: str
91 proxyjump:
92 description:
93 - Sets the C(ProxyJump) option.
94 - Mutually exclusive with O(proxycommand).
95 type: str
96 version_added: 6.5.0
97 forward_agent:
98 description:
99 - Sets the C(ForwardAgent) option.
100 type: bool
101 version_added: 4.0.0
102 add_keys_to_agent:
103 description:
104 - Sets the C(AddKeysToAgent) option.
105 type: bool
106 version_added: 8.2.0
107 ssh_config_file:
108 description:
109 - SSH config file.
110 - If O(user) and this option are not specified, C(/etc/ssh/ssh_config) is used.
111 - Mutually exclusive with O(user).
112 type: path
113 host_key_algorithms:
114 description:
115 - Sets the C(HostKeyAlgorithms) option.
116 type: str
117 version_added: 6.1.0
118 controlmaster:
119 description:
120 - Sets the C(ControlMaster) option.
121 choices: ['yes', 'no', 'ask', 'auto', 'autoask']
122 type: str
123 version_added: 8.1.0
124 controlpath:
125 description:
126 - Sets the C(ControlPath) option.
127 type: str
128 version_added: 8.1.0
129 controlpersist:
130 description:
131 - Sets the C(ControlPersist) option.
132 type: str
133 version_added: 8.1.0
134 dynamicforward:
135 description:
136 - Sets the C(DynamicForward) option.
137 type: str
138 version_added: 10.1.0
139 other_options:
140 description:
141 - Allows specifying arbitrary SSH config entry options using a dictionary.
142 - The key names must be lower case. Keys with upper case values are rejected.
143 - The values must be strings. Other values are rejected.
144 type: dict
145 version_added: 10.4.0
146 address_family:
147 description:
148 - Sets the C(AddressFamily) option.
149 choices: ['any', 'inet', 'inet6']
150 type: str
151 version_added: 13.0.0
152 requirements:
153 - paramiko
154 """
155
156 EXAMPLES = r"""
157 - name: Add a host in the configuration
158 community.general.ssh_config:
159 user: akasurde
160 host: "example.com"
161 hostname: "github.com"
162 identity_file: "/home/akasurde/.ssh/id_rsa"
163 port: '2223'
164 state: present
165 other_options:
166 serveraliveinterval: '30'
167
168 - name: Add SSH config with key auto-added to agent
169 community.general.ssh_config:
170 user: devops
171 host: "example.com"
172 hostname: "staging.example.com"
173 identity_file: "/home/devops/.ssh/id_rsa"
174 add_keys_to_agent: true
175 state: present
176
177 - name: Delete a host from the configuration
178 community.general.ssh_config:
179 ssh_config_file: "{{ ssh_config_test }}"
180 host: "example.com"
181 state: absent
182 """
183
184 RETURN = r"""
185 hosts_added:
186 description: A list of host added.
187 returned: success
188 type: list
189 sample: ["example.com"]
190 hosts_removed:
191 description: A list of host removed.
192 returned: success
193 type: list
194 sample: ["example.com"]
195 hosts_changed:
196 description: A list of host changed.
197 returned: success
198 type: list
199 sample: ["example.com"]
200 hosts_change_diff:
201 description: A list of host diff changes.
202 returned: on change
203 type: list
204 sample:
205 [
206 {
207 "example.com": {
208 "new": {
209 "hostname": "github.com",
210 "identityfile": [
211 "/tmp/test_ssh_config/fake_id_rsa"
212 ],
213 "port": "2224"
214 },
215 "old": {
216 "hostname": "github.com",
217 "identityfile": [
218 "/tmp/test_ssh_config/fake_id_rsa"
219 ],
220 "port": "2224"
221 }
222 }
223 }
224 ]
225 """
226
227 import os
228 from copy import deepcopy
229
230 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
231
232 from ansible_collections.community.general.plugins.module_utils._ssh import determine_config_file
233 from ansible_collections.community.general.plugins.module_utils._stormssh import (
234 HAS_PARAMIKO,
235 PARAMIKO_IMPORT_ERROR,
236 ConfigParser,
237 )
238
239
240 def convert_bool(value):
241 if value is True:
242 return "yes"
243 if value is False:
244 return "no"
245 return None
246
247
248 def fix_bool_str(value):
249 if value == "True":
250 return "yes"
251 if value == "False":
252 return "no"
253 return value
254
255
256 class SSHConfig:
257 def __init__(self, module):
258 self.module = module
259 if not HAS_PARAMIKO:
260 module.fail_json(msg=missing_required_lib("PARAMIKO"), exception=PARAMIKO_IMPORT_ERROR)
261 self.params = module.params
262 self.user = self.params.get("user")
263 self.group = self.params.get("group") or self.user
264 self.host = self.params.get("host")
265 self.config_file = self.params.get("ssh_config_file")
266 self.identity_file = self.params["identity_file"]
267 self.check_ssh_config_path()
268 try:
269 self.config = ConfigParser(self.config_file)
270 except FileNotFoundError:
271 self.module.fail_json(msg=f"Failed to find {self.config_file}")
272 self.config.load()
273
274 def check_ssh_config_path(self):
275 self.config_file = determine_config_file(self.user, self.config_file)
276
277 # See if the identity file exists or not, relative to the config file
278 if os.path.exists(self.config_file) and self.identity_file is not None:
279 dirname = os.path.dirname(self.config_file)
280 self.identity_file = os.path.join(dirname, self.identity_file)
281
282 if not os.path.exists(self.identity_file):
283 self.module.fail_json(msg=f"IdentityFile {self.params['identity_file']} does not exist")
284
285 def ensure_state(self):
286 hosts_result = self.config.search_host(self.host)
287 state = self.params["state"]
288 args = dict(
289 hostname=self.params.get("hostname"),
290 port=self.params.get("port"),
291 identity_file=self.params.get("identity_file"),
292 identities_only=convert_bool(self.params.get("identities_only")),
293 user=self.params.get("remote_user"),
294 strict_host_key_checking=self.params.get("strict_host_key_checking"),
295 user_known_hosts_file=self.params.get("user_known_hosts_file"),
296 proxycommand=self.params.get("proxycommand"),
297 proxyjump=self.params.get("proxyjump"),
298 host_key_algorithms=self.params.get("host_key_algorithms"),
299 forward_agent=convert_bool(self.params.get("forward_agent")),
300 add_keys_to_agent=convert_bool(self.params.get("add_keys_to_agent")),
301 controlmaster=self.params.get("controlmaster"),
302 controlpath=self.params.get("controlpath"),
303 controlpersist=fix_bool_str(self.params.get("controlpersist")),
304 dynamicforward=self.params.get("dynamicforward"),
305 address_family=self.params.get("address_family"),
306 )
307 if self.params.get("other_options"):
308 for key, value in self.params.get("other_options").items():
309 if key.lower() != key:
310 self.module.fail_json(msg=f"The other_options key {key} must be lower case")
311 if key not in args:
312 if not isinstance(value, str):
313 self.module.fail_json(
314 msg=f"The other_options value provided for key {key} must be a string, got {type(value)}"
315 )
316 args[key] = value
317 else:
318 self.module.fail_json(msg=f"Multiple values provided for key {key}")
319
320 config_changed = False
321 hosts_changed = []
322 hosts_change_diff = []
323 hosts_removed = []
324 hosts_added = []
325
326 hosts_result = [host for host in hosts_result if host["host"] == self.host]
327
328 if hosts_result:
329 for host in hosts_result:
330 if state == "absent":
331 # Delete host from the configuration
332 config_changed = True
333 hosts_removed.append(host["host"])
334 self.config.delete_host(host["host"])
335 else:
336 # Update host in the configuration
337 changed, options = self.change_host(host["options"], **args)
338
339 if changed:
340 config_changed = True
341 self.config.update_host(host["host"], options)
342 hosts_changed.append(host["host"])
343 hosts_change_diff.append(
344 {
345 host["host"]: {
346 "old": host["options"],
347 "new": options,
348 }
349 }
350 )
351 elif state == "present":
352 changed, options = self.change_host(dict(), **args)
353
354 if changed:
355 config_changed = True
356 hosts_added.append(self.host)
357 self.config.add_host(self.host, options)
358
359 if config_changed and not self.module.check_mode:
360 try:
361 self.config.write_to_ssh_config()
362 except PermissionError as perm_exec:
363 self.module.fail_json(msg=f"Failed to write to {self.config_file} due to permission issue: {perm_exec}")
364 # Make sure we set the permission
365 perm_mode = "0600"
366 if self.config_file == "/etc/ssh/ssh_config":
367 perm_mode = "0644"
368 self.module.set_mode_if_different(self.config_file, perm_mode, False)
369 # Make sure the file is owned by the right user and group
370 self.module.set_owner_if_different(self.config_file, self.user, False)
371 self.module.set_group_if_different(self.config_file, self.group, False)
372
373 self.module.exit_json(
374 changed=config_changed,
375 hosts_changed=hosts_changed,
376 hosts_removed=hosts_removed,
377 hosts_change_diff=hosts_change_diff,
378 hosts_added=hosts_added,
379 )
380
381 @staticmethod
382 def change_host(options, **kwargs):
383 options = deepcopy(options)
384 changed = False
385 for k, v in kwargs.items():
386 if "_" in k:
387 k = k.replace("_", "")
388
389 if not v:
390 if options.get(k):
391 del options[k]
392 changed = True
393 elif options.get(k) != v and not (isinstance(options.get(k), list) and v in options.get(k)):
394 options[k] = v
395 changed = True
396
397 return changed, options
398
399
400 def main():
401 module = AnsibleModule(
402 argument_spec=dict(
403 group=dict(type="str"),
404 host=dict(type="str", required=True),
405 hostname=dict(type="str"),
406 host_key_algorithms=dict(type="str", no_log=False),
407 identity_file=dict(type="path"),
408 identities_only=dict(type="bool"),
409 other_options=dict(type="dict"),
410 port=dict(type="str"),
411 proxycommand=dict(type="str"),
412 proxyjump=dict(type="str"),
413 forward_agent=dict(type="bool"),
414 add_keys_to_agent=dict(type="bool"),
415 remote_user=dict(type="str"),
416 ssh_config_file=dict(type="path"),
417 state=dict(type="str", default="present", choices=["present", "absent"]),
418 strict_host_key_checking=dict(type="str", choices=["yes", "no", "ask", "accept-new"]),
419 controlmaster=dict(type="str", choices=["yes", "no", "ask", "auto", "autoask"]),
420 controlpath=dict(type="str"),
421 controlpersist=dict(type="str"),
422 dynamicforward=dict(type="str"),
423 user=dict(type="str"),
424 user_known_hosts_file=dict(type="str"),
425 address_family=dict(type="str", choices=["any", "inet", "inet6"]),
426 ),
427 supports_check_mode=True,
428 mutually_exclusive=[
429 ["user", "ssh_config_file"],
430 ["proxycommand", "proxyjump"],
431 ],
432 )
433
434 ssh_config_obj = SSHConfig(module)
435 ssh_config_obj.ensure_state()
436
437
438 if __name__ == "__main__":
439 main()