Debian Codegraph @

ansible_collections/azure/azcollection/plugins/plugin_utils/ssh_info.py

raw symbols SCIP
1 # --------------------------------------------------------------------------------------------
2 # Copyright (c) Microsoft Corporation. All rights reserved.
3 # Licensed under the MIT License. See License.txt in the project root for license information.
4 # --------------------------------------------------------------------------------------------
5
6
7 import os
8 from ansible_collections.azure.azcollection.plugins.plugin_utils import file_utils
9 from ansible_collections.azure.azcollection.plugins.plugin_utils import connectivity_utils
10
11
12 class ConfigSession():
13 # pylint: disable=too-many-instance-attributes
14 def __init__(self, ssh_config_file, ssh_relay_file, resource_group_name, hostname, ansible_host,
15 private_key_file, local_user, port, resource_type, ssh_proxy_folder):
16 self.resource_group_name = resource_group_name
17 self.hostname = hostname
18 self.ansible_host = ansible_host
19 self.local_user = local_user
20 self.port = port
21 self.resource_type = resource_type
22 self.proxy_path = None
23 self.relay_info = None
24 self.relay_info_path = None
25 self.ssh_config_file = os.path.abspath(os.path.expanduser(ssh_config_file))
26 self.ssh_relay_file = os.path.abspath(os.path.expanduser(ssh_relay_file))
27 self.private_key_file = os.path.abspath(os.path.expanduser(private_key_file)) if private_key_file else None
28 self.ssh_proxy_folder = os.path.abspath(os.path.expanduser(ssh_proxy_folder)) if ssh_proxy_folder else None
29
30 def get_config_text(self):
31 lines = [""]
32 self.relay_info_path = self._create_relay_info_file()
33 lines = lines + self._get_arc_entry()
34 return lines
35
36 def _get_arc_entry(self):
37 lines = []
38 lines.append("Host " + self.ansible_host)
39 lines.append("\tHostName " + self.hostname)
40 lines.append("\tUser " + self.local_user)
41 if self.private_key_file:
42 lines.append("\tIdentityFile \"" + self.private_key_file + "\"")
43 if self.port:
44 lines.append("\tProxyCommand \"" + self.proxy_path + "\" " + "-r \"" + self.relay_info_path + "\" "
45 + "-p " + str(self.port))
46 else:
47 lines.append("\tProxyCommand \"" + self.proxy_path + "\" " + "-r \"" + self.relay_info_path + "\"")
48 return lines
49
50 def _create_relay_info_file(self):
51 relay_info_path = self.ssh_relay_file
52 relay_info_dir = os.path.dirname(relay_info_path)
53 if not os.path.isdir(relay_info_dir):
54 os.makedirs(relay_info_dir)
55
56 # Overwrite relay_info if it already exists in that folder.
57 file_utils.delete_file(relay_info_path, f"{relay_info_path} already exists, and couldn't be overwritten.")
58 file_utils.write_to_file(relay_info_path, 'w', connectivity_utils.format_relay_info_string(self.relay_info),
59 f"Couldn't write relay information to file {relay_info_path}.", 'utf-8')
60 os.chmod(relay_info_path, 0o644)
61
62 return relay_info_path