4

Is there a semi-easy way to use Ansible to open an interactive session?

I've spent a good amount of time making use of keys and other credentials stores to make a stellar ansible inventory file. Problem is, when I want to get on the servers that I can easily manage, I've gotta go out and find those creds and take the time to log into them.

It's almost easier for me just to run adhoc commands with ansible instead of logging in via ssh. Is there a way to pause ansible with a running interactive session so I can get a command prompt? I noticed that sometimes it lets me accept host keys, but other times it bombs out, (I think this happens when running ssh proxy), so I know things can be done interactively.

1
  • The host_key acceptance is a local prompt done before connection. Long strory short: no, you can't have interactive ssh sessions inside ansible. At best you can have prompts before a play starts (vars_prompt play section) or during run (prompt module). – Zeitounator Jan 17 '20 at 16:32
1

You could try ansinble-console

It mostly feels like you just have a shell open, unless you use and ansible task name as your command, in which case prefixing it with shell <whatever you wanted to run> should work.

1
  • Although it is not interactive as stated in the command help, +1 because it is really getting close. Thanks for that one. – Zeitounator Feb 29 '20 at 22:14
1

I recently made myself a small script that seems to do the work. It certainly can be done better but maybe you can get some inspiration:

#!/bin/bash

set -e

if [ -z "$1" ]
 then
    echo "No host patter supplied. Please provide a host pattern that would match only one host form the inventory."
    echo "Usage: ansible-ssh <host_pattern>"
    echo "Example: ./ansible-ssh services[0]"
    exit 1
fi

USER=sysadm
HOST_PATTERN=$1
HOST=`ansible -m shell -a "echo {{ groups.$HOST_PATTERN }}" localhost  | sed 1d`

if grep -q "\[.*\]" <<< "$HOST"; then
  echo "Host pattern $HOST_PATTERN matches more than one host: $HOST"
  exit 1
fi

echo "Connecting to $USER@$HOST..."
ssh $USER@$HOST

Just edit your default USER (in my case sysadm) and execute in the following way:

./ansible-ssh services[0]

Where services is your inventory entry holding one or more IPs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.