Created
December 23, 2016 14:51
-
-
Save phaer/dc7aafbfd4809fae27862a04e8f4e564 to your computer and use it in GitHub Desktop.
connection_plugin for Ansible and FreeBSD jails, connecting through ssh on the jailhost.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# connection_plugin for Ansible and FreeBSD jails, connecting | |
# through ssh on the jailhost. | |
# inspiration: https://github.com/austinhyde/ansible-sshjail | |
from ansible.errors import AnsibleError | |
from ansible.plugins.connection import ConnectionBase | |
from ansible.plugins.connection import ssh | |
try: | |
from __main__ import display | |
except ImportError: | |
from ansible.utils.display import Display | |
display = Display() | |
class Connection(ConnectionBase): | |
transport = 'sshjail' | |
has_pipelining = False # TODO: Check pipelining | |
def __init__(self, play_context, *args, **kwargs): | |
super(Connection, self).__init__(play_context, *args, **kwargs) | |
try: | |
self.name, self.host = play_context.remote_addr.split('@') | |
except ValueError: | |
raise AnsibleError('remote address not in jail@host format.') | |
play_context.remote_addr = self.host | |
self.ssh = ssh.Connection(play_context, *args, **kwargs) | |
self.jail_info = self._info(self.name) | |
self.jid = int(self.jail_info['jid']) | |
self.path = self.jail_info['path'] | |
def _parse_properties(self, line): | |
"""parses a string of 'k=v' pairs into a dictionary""" | |
for param in line.split(): | |
try: | |
k, v = param.split('=') | |
except ValueError: | |
k, v = param, True | |
yield k, v | |
def _info(self, name): | |
"""properties returned by jls for the given jail""" | |
rc, out, err = self.ssh.exec_command('jls -s') | |
if rc != 0: | |
raise AnsibleError('could not execute "jls": %s' % err) | |
for jail in out.split('\n'): | |
properties = dict(self._parse_properties(jail)) | |
if 'host.hostname' in properties \ | |
and properties['host.hostname'] == name: | |
return properties | |
raise AnsibleError('could not find a jail named "%s"' % name) | |
def _connect(self): | |
super(Connection, self)._connect() | |
def exec_command(self, command, *args, **kwargs): | |
cmd = 'jexec -l %d sh -c "%s"' % (self.jid, command) | |
return self.ssh.exec_command(cmd, *args, **kwargs) | |
def put_file(self, in_path, out_path): | |
return self.ssh.put_file(in_path, self.path + out_path) | |
def fetch_file(self, in_path, out_path): | |
return self.ssh.put_file(self.path + in_path, out_path) | |
def close(self): | |
self.ssh.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment