Guide to SSH Management: How to Automate Your Foreman Hosts

SSH Management - Foreman

Guide to SSH Management: How to Automate Your Foreman Hosts

Why type when you can script? If you’re managing a ton of servers through Foreman and manually editing your ~/.ssh/config, stop right now! There’s a better way. This script will automatically generate your SSH configuration, making it easier than ever to connect to your managed hosts.
Let’s be honest: sysadmins love automation, but we also love convenience. Why waste time looking up hostnames when you can press Tab and get instant SSH access?

What is SSH and how does it work

Let’s start with the basics.

SSH (Secure Shell) is a method that allows secure connection to a remote computer over a network. Think of it as a safe version of a remote control for another computer. When you use SSH, all the information you send and receive is encrypted, protecting it from unauthorized access.

This technology is especially useful for system administrators who need to manage servers remotely, as well as anyone who wants to securely transfer files or data between computers. Before SSH, tools like Telnet and FTP were used for similar purposes, but they did not provide encryption. This meant that data could be intercepted and read. Secure Shell was introduced to solve this problem by providing a secure communication channel.

In a nutshell, SSH works by allowing a user (client) to start a connection with a remote computer (server). The server responds by sending a public key, and then the client and server establish a secure, encrypted connection together. Once the connection is established, the user can safely manage the remote computer or transfer files.

Use Foreman for automating tasks

Foreman is a server management tool that helps automate tasks like software installation, configuration, and updates. It is used to manage a large number of computers (servers) from one central point.

So, when we say “automate your Foreman Hosts,” it means you can use SSH to remotely manage servers that are controlled by Foreman, all in an automated way. In other words, instead of manually managing each server one by one, Foreman allows you to do it quickly and efficiently.

When managing multiple hosts via Foreman, you likely:

  • Need to SSH into them often.
  • Manually update your ~/.ssh/config file.
  • Forget hostnames or get tired of typing them.

Now, let’s jump into the steps.

Step 1: Connect to Foreman and Retrieve Hosts

 Before we automate anything, make sure you can connect to your Foreman server. Run this command to test:

ssh foremanadmin@foreman.example.com

Step 2: Fetch Hosts from Foreman

hammer host list | awk '{print $3}' | tail -n +1 > forema_inventory.txt

Now, open foreman_inventory.txt and verify that it only contains hostnames, like this:

server1.example.com
server2.example.com
server3.example.com

Step 3: Generate an SSH Configuration from the Inventory File

Now let’s automate our SSH configuration with the following script:

#!/bin/bash

# Define default SSH user (modify as needed)
DEFAULT_USER="root"

# Input inventory file path
inventory_file="$HOME/forema_inventory.txt"

# Output SSH config file path
ssh_config_file="$HOME/.ssh/config"

# Ensure inventory file exists
if [ ! -f "$inventory_file" ]; then
echo " Error: Inventory file '$inventory_file' not found!"
exit 1
fi

# Start fresh by clearing the SSH config file
echo "# Auto-generated SSH config" > "$ssh_config_file"

# Loop through each line in the inventory file
while read -r host; do
# Skip empty lines
[[ -z "$host" ]] && continue

# Append host entry to SSH config using full hostname
echo "Host $host" >> "$ssh_config_file"
echo " HostName $host" >> "$ssh_config_file"
echo " User $SSH_USER" >> "$ssh_config_file"
echo "" >> "$ssh_config_file" # Blank line for readability
done < "$inventory_file"

Run this script, and your SSH configuration will be updated automatically.

Step 4: Enable SSH Auto-Completion

To make our lives even easier, let’s enable SSH auto-completion so we can just start typing a hostname and hit TAB to auto-complete.

Add this to your ~/.bashrc:

if [ -f /usr/share/bash-completion/completions/ssh ]; then
. /usr/share/bash-completion/completions/ssh
fi

Then apply the changes:

source ~/.bashrc

Now, try typing:

ssh <hostname>

and press TAB twice to see auto-suggestions.

With this setup, you’ve successfully automated SSH access to your Foreman managed hosts, eliminating manual config edits and making your workflow more efficient.

Set up your configuration

Now, let’s wrap things up in one script with prompts to automate everything, so you can set up your SSH configuration in just a few seconds—no manual steps required:

 #!/bin/bash


# Prompt for Foreman SSH details
read -rp "Enter Foreman SSH Host (e.g., foreman.example.com): " FOREMAN_HOST
read -rp "Enter Foreman SSH User (e.g., foremanadmin): " FOREMAN_USER


# Prompt for default SSH user (for generated config)
read -rp "Enter default SSH user for managed hosts (press Enter for 'root'): " SSH_USER
SSH_USER=${SSH_USER:-root} # Default to root if left blank


# Ask if the user wants to back up the existing SSH config
read -rp "Would you like to back up the existing SSH config? (yes/no): " BACKUP_CHOICE


# Define paths
inventory_file="$HOME/.ssh/hosts_list.txt"
ssh_config_file="$HOME/.ssh/config"


# Ensure Foreman is reachable
echo "Connecting to $FOREMAN_USER@$FOREMAN_HOST to fetch hosts..."
if ! ssh -o BatchMode=yes -o ConnectTimeout=5 "$FOREMAN_USER@$FOREMAN_HOST" "echo Foreman reachable"; then
echo " Error: Cannot connect to Foreman at $FOREMAN_HOST. Check SSH access."
exit 1
fi


# Fetch hosts from Foreman using SSH
echo " Running 'hammer host list' on $FOREMAN_HOST..."
ssh "$FOREMAN_USER@$FOREMAN_HOST" "hammer host list | awk '{print \$3}' | tail -n +1" > "$inventory_file"


# Ensure file is not empty
if [ ! -s "$inventory_file" ]; then
echo " Error: No hosts retrieved from Foreman."
exit 1
fi


echo " Hosts list saved to $inventory_file."


# Handle SSH config backup based on user input
if [[ "$BACKUP_CHOICE" =~ ^[Yy][Ee]?[Ss]?$ ]]; then
cp "$ssh_config_file" "$ssh_config_file.bak"
echo " Backup of existing SSH config saved as ~/.ssh/config.bak"
fi


# Check if SSH completion is already in .bashrc
grep -qF '/usr/share/bash-completion/completions/ssh' ~/.bashrc || echo -e '\nif [ -f /usr/share/bash-completion/completions/ssh ]; then\n . /usr/share/bash-completion/completions/ssh\nfi' >> ~/.bashrc


# Start writing new SSH config
echo "# Auto-generated SSH config from Foreman ($FOREMAN_HOST)" > "$ssh_config_file"


# Loop through each line in the inventory file
while read -r host; do
# Skip empty lines
[[ -z "$host" ]] && continue


# Append host entry to SSH config using full hostname
echo "Host $host" >> "$ssh_config_file"
echo " HostName $host" >> "$ssh_config_file"
echo " User $SSH_USER" >> "$ssh_config_file"
echo "" >> "$ssh_config_file" # Blank line for readability
done < "$inventory_file"

echo ” SSH config updated! Try connecting with: ssh <type first letters of hostname> + <press TAB twice>

 

Here’s how our script and prompts look in action: a simple, interactive setup that guides you through every step effortlessly:

SSH Management -automate your Foreman Host

Finally, simply refresh your shell with source ~/.bashrc and seamlessly SSH into your servers with ease and efficiency every time.

Conclusion

With the script and steps outlined in this guide, you can successfully automate SSH access to your Foreman hosts. Taking advantage of the power of automation, you can quickly and easily manage multiple servers. This means you no longer have to manually edit configuration files, which saves you time and effort. With automation, managing multiple servers becomes faster and easier, letting you focus on more important tasks.

Need more Foreman automation tips? Send us an email or subscribe to our newsletter.

Share this post