Skip to content

Instantly share code, notes, and snippets.

@vrischmann
Created July 15, 2018 13:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrischmann/365ad29ddc7126bd6fcbdab8e7c8fcce to your computer and use it in GitHub Desktop.
Save vrischmann/365ad29ddc7126bd6fcbdab8e7c8fcce to your computer and use it in GitHub Desktop.
Automate SSH sessions to some hosts from an Ansible inventory using tmux

What it does

This script automates launching SSH sessions to hosts defined in an Ansible inventory file.

It parses the inventory file (at ./hosts) and understand Ansible patterns like webserver[0:1],db[4:10]:!db9.stuff.com.

So if you have this inventory for example:

[webserver]
webserver01.stuff.com
webserver02.stuff.com
webserver03.stuff.com

db
foo.stuff.com
bar.stuff.com

And you run main.py db[0],webserver[0:1] then it will do this:

  • create a new tmux window
  • create a new pane for each host matched (3 in this example) running ssh to the host
  • retiling the window
  • go the first pane
  • enable synchronized input (meaning what you type is replicated in all panes for this window)
#!/usr/bin/env python
from collections import namedtuple
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
import argparse
import logging
import sys
import os
import subprocess
def run(args):
try:
output = subprocess.check_output(args)
except subprocess.CalledProcessError:
logging.error("unable to run command")
logging.error(output)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description="Launch ssh sessions to some hosts inside a tmux session")
parser.add_argument('host_pattern', metavar='PATTERN', type=str)
args = parser.parse_args()
# Get the hosts
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources="./hosts")
hosts = inventory.get_hosts(args.host_pattern)
if len(hosts) == 0:
logging.error("no hosts match the pattern {}".format(args.host_pattern))
sys.exit(1)
# Run tmux
run(["tmux", "new-window", "ssh \"{}\"".format(args.host_pattern)])
for host in hosts:
run(["tmux", "split-window", "-h", "ssh {}".format(host)])
run(["tmux", "select-layout", "tiled"])
run(["tmux", "select-pane", "-t", "0"])
run(["tmux", "set-window-option", "synchronize-panes", "on"])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment