Tuesday, April 22, 2025

Ansible Journey 2: SSH Connectivity

SSH is the common tool for logging into one host from another. It is found on every version of Linux, and generally installed and set to start when the server starts. This is the default mechanism for Ansible to issue commands for other servers on the network. As such, it is both powerful, and incredibly dangerous. In most cases, we use a password or passphrase to connect from one host to another. If we use either with Ansible to connect to target hosts, we end up defeating the purpose of automation – to manage systems without human intervention.

In the prior post, I mentioned that Ansible works, whether we are in the office, or in bed. It wouldn’t do us much good to get an alert in the middle of the night because Ansible is attempting to execute some action, but is paused while waiting for a password. So, this requires setting up a passwordless authentication system, such that Ansible can make the connection, and issue the command(s) on the target without human intervention. Passwordless authentication removes one security block (the password) so you will need to secure access to the Ansible host and admin account in other ways. This is beyond the scope of this tutorial.

The following bash shell script, when executed on a host, will create that account, it's .ssh directory, and give it the permissions necessary to execute any command as if it were root:

#!/bin/bash

useradd ansadm
ssh_dir=/home/ansadm/.ssh
mkdir $ssh_dir && chmod 700 $ssh_dir

file=/etc/sudoers.d/ansadm
touch $file
chown root:root $file && chmod 440 $file && echo "ansadm ALL=(ALL) NOPASSWD: ALL" > $file

Account creation outside of Ansible is beyond the scope of this tutorial, but I'll cover at a high level what we are doing and why.

When saved as a shell script and given execute permissions, this can be run on any host (in fact, it will need to be run on every host except the ansible cont4ol host) where the ansible admin (ansadm) needs to exectute commands. First, we create the account, and ensure its .ssh directory is available. Next, we create a sudoers file for ansadm, and drop that in place so ansadm can obtain elevated permissions. This is all done in a secure way, such that permissions are not granted until the files are properly secured with permissions and ownership.

We need the .ssh directory to be in place before we use ansible to copy over the ansadm's public key.n This is because the authorized_key module will not create an .ssh directory as of this writing. Then, we drop in the file that gives ansadm permissions to execute any command. AS shown, that file has just one line:

ansadm ALL=(ALL) NOPASSWD: ALL


With that out of the way, we can begin using ansible to automate tasks.


<PREV - CONTENTS - NEXT>

 

No comments:

Post a Comment