Each deployment is controlled by bash scripts as a simple command-line based interface to getting stuff done. The first step of setting up a new deployment is to create the scripts and config files which will call the Ansible playbooks with the appropriate parameters.

Deployment

The design of the Deployer means each deployment is relatively self contained. There are some shared components and config but there is no central control and ultimately it is up to each individual deployment if and how they use them which reduces the single points of failure and also enables faster evolution as I shouldn't have to worry about upgrading everything else at the same time.

All the files for each deployment go into a single directory under /ansible/playbooks and two bash scripts control the process.

  1. A launcher script that is called by the operator (me!) to trigger a deployment.
  2. A deploy script that is called by the launcher to actually performs the deployment, calling the Ansible playbooks (and any other tools needed).

This split into launch and deploy scripts means the launcher script can also call the deploy script for other deployments, so for example the Nextcloud launcher can call the Ubuntu deploy script first to upload and configure an OVF template before its own Nextcloud-specific deploy script to install and configure Nextcloud.

As mentioned in Building the Deployer there is also an automation/deploy directory that is intended to provide a central location for triggering a deployment. As this is very much an Ansible-centric process at the moment this just contains links to the launcher script. If I was to add other tooling in future, then in principle each tool would have it's own top-level under /automation and then a similar structure with reusable components in known locations that can be called. The automation/deploy directory might have a script or a link that calls a component of the new tool instead so I wouldn't have to remember which tool initiates a deployment and it also saves a bit of typing which is always nice.

Preparing a Deployment

Deployment filesThe first step is to create a directory for our deployment scripts and playbooks, and since I use git to manage the playbooks I also need to prepare that too. I'm also trying to keep the names consistent with a similar structure to the templates. For this general Ubuntu 24.04 deployment I'm going with u2404base as the name.

Since I'm using git source control I can have different versions of the Ubuntu base deployer. To save switching between them depending if I'm working on updates or just want to use it then I can have each version (aka branch in git-speak) in a separate directory, so I'm also going to create u2404base-dev.

This means u2404base should be stable and always available for doing a deployment without having to maintain a second runtime version of the everything and I'm still free to work with a dev, or even multiple development versions without breaking anything.

Reality Check: This is based on a previous incarnation of the deployer so I already have this in my git repository. So in real life I created new branches for Ubuntu24 and Ubuntu24-dev and checked them out into the u204base and u2404base-dev directories respectively and then started making changes. But for the purposes of this article I'm assuming we're starting afresh and working in the u2404base-dev directory (and branch) while we set this up.

Subdirectories

As this is based around Ansible then we need to create a couple of subdirectories and some configuration to keep Ansible happy.

roles : This will keep all the roles that our playbooks require. A role is a reusable bit of Ansible code that can be shared between many different playbooks.

vars : Some of the playbooks have some standard parameters held in variable files which by convention are held in a vars subdirectory

.gitignore

Since I already keep roles in their own git repositories and let Ansible install them on demand I don't want to keep them in my Ubuntu playbook repository too. To stop git complaining about the roles I can define the roles directory in a .gitignore file our playbook directory.

# git ignore file
/roles/*
!/roles/requirements.yaml
!/roles/local_*

These are all Ansible-specific and I'll come to that later once we start building the playbooks.

During development I sometimes want to put some content into a role rather than directly into a playbook so I prefix those roles with local_ which means I need to put an ignore on the ignore so the local role files really are managed by git.

 

ansible.cfg

This is a small ansible configuration file that sits in our playbook directory. For the deployment playbooks I'm using it to make sure that the roles I import go to the roles directory of the playbook concerned and not my home directory.

[defaults]
roles_path = ./roles

 

Refresh roles script

This is just a utility script to trigger an update of the roles used in these this playbooks (providing I've maintained the requirements.yaml file) and it has the unimaginative name of refresh-roles.sh.

#!/bin/bash
echo "Refreshing Ansible roles from requirements.yaml"
echo ""
echo "For first run of the playbook manually install collections:"
echo "ansible-galaxy collection install -r ./roles/requirements.yaml"
echo ""

ansible-galaxy install -f -r ./roles/requirements.yaml

Launcher script - Ubuntu OS Base

This script runs the entire Ubuntu 24.04 base deployment. It sources configuration files so we shouldn't have to modify the script itself to update any config and calls the deploy script. As we'll see later in a Nextcloud example we can call the deploy scripts from other deployments in sequence so we can reuse deployments rather than having to do everything from scratch each time.

Human Launch script Deploy script Playbooks Comment
Update inventory        
Execute launch script source script config      
source ansible config      
Call deploy script for OS Lock deployment   Wait until we can get a deployment lock
Call playbook - deploy Call ovftool to import VM from VMtemplates library Executes on ansible controller
call playbook - build Rename and reboot VM  
Unlock deployment   Release lock for next deployment to proceed
call playbook - build Base config and reboot  
call playbook - build Domain join or create local ansible user  
call playbook - admin Configure optional utils e.g. backup  
call playbook - admin Delete build user and clean up  
Start using new system        

 

ubuntu24.conf

This is a configuration file that is sourced by the ubuntu24.sh script and sets some standard parameters for this deployment so I can make some changes such as a different template hostname and initial login without having to keep customising the script itself.

# Config file included by ubuntu24.sh
# This provides parameters to the launcher script

# Ansible vars files with ESXi details
export ESX_DEPLOY="@../../control/newhost/esx-deploy.yaml"

# Hostname of a freshly deployed template. Domain name is an input parameter.
export OVF_HOSTNAME=u2404-base-1

# User for SSH password login for playbook 1
export TARGET_BUILD_SSH_USER=template-build-user
export TARGET_BUILD_SSH_KEY=../../control/newhost/template-build-user

# User and their key location for SSH login after playbook 1
export TARGET_ADMIN_SSH_USER=automation-user
export TARGET_ADMIN_SSH_KEY=../../control/automation-user

The esx-deploy.yaml file contains the path to the OVF tool and base directory for the OFV templates as both could be specific to the control node this is running on. I originally had the ESXi hostname and credentials in there too but they've since been moved to the inventory (vaulted of course!).

The OVF_HOSTNAME is the hostname set in the template and the VM will use this name on the first boot after being imported, which we then change in the next playbook to run.

The TARGET_BUILD_SSH parameters specify the user and key Ansible should use for the first part of the deploy process, the TARGET_ADMIN parameters specify the user and key Ansible should use for the later part of the deploy process, which is also the user that Ansible should use for subsequent deployers and admin of this VM.

ansible-env.sh

This sets ansible-specific configuration and may be executed directly if you want to call playbooks directly from the command line. It's likely this file will be the same in every deployment and probably on any other Deployers too. 

#!/bin/bash
echo "Setting Ansible LIVE environment for new hosts processing"
# echo "Make sure you did:  source ./ansible-env.sh else it won't work"
export ANSIBLE_INVENTORY=../../inventory/live
export ANSIBLE_HOST_KEY_CHECKING=False
export ANSIBLE_VAULT_PASSWORD_FILE=../../control/vault-newhost

The inventory needs to be available in the directory specified - this is also in a git repo. The vault password is also in the control directory as several deployers user it and I don't want that getting accidentally uploaded into a git repo either. In a real production scenario that should probably be requested from a secret management service rather than left in a file on the control node.

The most likely change to this file is if I wanted to use a different Ansible inventory for a dev or test version of a deployment.

ubuntu24.sh

This is the script that you run to trigger a deployment.

It pulls in the deployment and ansible configurations, checks we've passed two parameters which should be host name and domain name of the target VM and calls the deployer script ubuntu24-deploy.sh to run the deployment. I use a similar script for building Nextcloud servers that also calls the ubuntu24-deploy.sh script before calling a nextcloud-specific deployer.

To use it I would do something similar to ubuntu24.sh dvu-s4fs-1 sandpit.example.com having first created an inventory entry for dvu-s4fs-1.sandpit.example.com with the required parameters.

#!/bin/bash
echo ""
echo "This will launch the deployment of a new Ubuntu 24.04 LTS virtual machine."
echo ""
echo "Setting environment..."

TARGET_HOST=""
TARGET_DOMAIN=""

# Import configuration for this script and ansible environment

source ./ubuntu24.conf

source ./ansible-env.sh
 
if [[ $# -ne 2 ]]; then
  echo ""
  echo "Please specify the hostname and the domain name"
  echo "e.g.   ubuntu24.sh myhost mydomain.example.com"
  echo ""
  exit
else
  TARGET_HOST=$1
  TARGET_DOMAIN=$2
fi

echo ""
echo "Launching deployment scripts..."
echo ""

./ubuntu24-deploy.sh $TARGET_HOST.$TARGET_DOMAIN $OVF_HOSTNAME.$TARGET_DOMAIN
DEPLOY_OK=$?

if [[ $DEPLOY_OK == 0 ]]; then
  echo ""
  echo "------------------------"
  echo "Ubuntu Build Complete"
  echo ""
else
  echo ""
  echo "------------------------"
  echo "Ubuntu Build Failed : $DEPLOY_OK"
  echo ""
  exit $DEPLOY_OK
fi

 

Deploy script

The deploy script is the workhorse of the two bash scripts. Its job is to call the playbooks for each stage of the deployment, providing the previous one completed successfully.

Human Launch script Deploy script Playbooks Comment
Update inventory        
Execute launch script source script config      
source ansible config      
Call deploy script for OS Lock deployment   Wait until we can get a deployment lock
Call playbook - deploy Call ovftool to import VM from VMtemplates library Executes on ansible controller
call playbook - build Rename and reboot VM  
Unlock deployment   Release lock for next deployment to proceed
call playbook - build Base config and reboot  
call playbook - build Domain join or create local ansible user  
call playbook - admin Configure optional utils e.g. backup  
call playbook - admin Delete build user and clean up  
Start using new system        

 

I use bash functions to launch the playbooks and check for success since it's the same process to launch a playbook although this uses three variations depending on the input parameters they require.

The first part initialises some variables and outputs confirmation of what's been requested so the operation knows what is about to happen. 

#!/bin/bash
echo "################################################################################"
echo "#"
echo "#   Deploy Ubuntu 24.04 LTS VM to ESXi"
echo "#"
echo "#   Running Ansible Playbooks to prepare a new Ubuntu 24.04 LTS installation."
echo "#   This playbook uses prepared image"
echo "#"

# Validation performed by calling script
TARGET_HOST_FULL=$1
OVF_HOSTNAME_FULL=$2

PING_RET=255
LOCK_FILE=/tmp/deploylock-ubuntu2404.txt

# Via environment exports in launcher script
# OVF_HOSTNAME=
# TARGET_BUILD_SSH_USER=
# TARGET_BUILD_SSH_KEY=
# TARGET_ADMIN_SSH_USER=
# TARGET_ADMIN_SSH_KEY=

echo ""
echo "Launch parameters:"
echo ""
echo "   Target Host: $TARGET_HOST_FULL"
echo "   Template Host: $OVF_HOSTNAME_FULL"
echo ""
echo "   Initial user: $TARGET_BUILD_SSH_USER"
echo "   Ansible key: $TARGET_BUILD_SSH_KEY"
echo ""
echo "   Inventory: $ANSIBLE_INVENTORY"
echo "   Vault Key: $ANSIBLE_VAULT_PASSWORD_FILE"
echo ""

echo "For first run of the playbook manually install collections:"
echo "ansible-galaxy collection install -r ./roles/requirements.yaml"
echo "Use the refresh-roles.sh script to get latest versions of the roles for this playbook"
echo ""

#######################################
# Bash functions for this script
#

This function is called after the deployment has been locked and executes the deploy playbook whos tasks are configured to run on the Deployer itself. It also passes in the esx-deploy variable file from the control directory.

If ansible-playbook reports an error it calls the unlock script before forcing the script to exit with a failure.

RunPlaybookDeploy () {
# Run the deploy playbook

  local PLAYBOOK=$1

  local PING_RET=255
  local PLAYBOOK_RET="x"


  echo ""
  echo "----------------------------------------------------------"
  echo "- Running deploy playbook $PLAYBOOK for $TARGET_HOST_FULL"
  echo "-"
  echo "-"

  # No key or user needed as it is triggered from the control node
  ansible-playbook -v $PLAYBOOK --extra-vars "target=$TARGET_HOST_FULL" --extra-vars "@../../control/newhost/esx-deploy.yaml"
  
  PLAYBOOK_RET=$?
  if [[ $PLAYBOOK_RET == 0 ]]; then
    echo "Playbook $PLAYBOOK reported success for $TARGET_HOST_FULL"
    echo ""
  else
    echo "Playbook $PLAYBOOK reported error $PLAYBOOK_RET for $TARGET_HOST_FULL, stopping."
    echo ""

    DeployUnlock
    exit $PLAYBOOK_RET
  fi

  echo "#"
  echo "# Waiting for $TARGET_HOST_FULL to finish booting..."
  echo "#"

  while [ $PING_RET -gt 0 ]; do
    echo -e "$(date): Waiting a minute for $OVF_HOSTNAME"
    sleep 30s
 
    ping -c 3 -i 10 $OVF_HOSTNAME_FULL
    PING_RET=$?
  done

}

This function is called after the OVF template has been deployed but with the Deployer still locked and executes a playbook that renames the newly deployed VM from the hostname in the template to what it should really be. For this it needs to pass to Ansible the key and user to use, overide the hostname to uese for the connection to the template hostname by setting ansible_host and also passing in the expected hostname of the template so the playbook can validate the host it has connected to really is a newly deployed template just in case something has got messed up with name resolution. Thankfully that's not happened on any live deployments.


RunPlaybookConnectSSH () {
# Run playbook using alternative connection

  local PLAYBOOK=$1
  local SSH_USER=$2
  local SSH_KEY=$3

  local PLAYBOOK_RET="X"

  echo ""
  echo "----------------------------------------------------------"
  echo "- Running $PLAYBOOK for $TARGET_HOST_FULL via $OVF_HOSTNAME_FULL"
  echo "- "
  echo "-"

  ansible-playbook -v --private-key $SSH_KEY -u $SSH_USER $PLAYBOOK --extra-vars ansible_host=$OVF_HOSTNAME_FULL --extra-vars target=$TARGET_HOST_FULL --extra-vars ovf_hostname=$OVF_HOSTNAME

  PLAYBOOK_RET=$?
  if [[ $PLAYBOOK_RET == 0 ]]; then
    echo "Playbook $PLAYBOOK reported success for $TARGET_HOST_FULL"
    echo ""
  else
    echo "Playbook $PLAYBOOK reported error $PLAYBOOK_RET for $TARGET_HOST_FULL, stopping."
    echo ""
    DeployUnlock
    exit $PLAYBOOK_RET
  fi

} 

This is the usual playbook execution function that just needs the user and key and the host to operate on.

RunPlaybookSSH () {
# Run a playbook as given user and SSH key.

  local PLAYBOOK=$1
  local SSH_USER=$2
  local SSH_KEY=$3
  
  local PLAYBOOK_RET="X"

  echo "----------------------------------------------------------"
  echo "- Running $PLAYBOOK for $TARGET_HOST_FULL"
  echo "- "
  echo "-"
  
  ansible-playbook -v --private-key $SSH_KEY -u $SSH_USER $PLAYBOOK --extra-vars target=$TARGET_HOST_FULL 

  PLAYBOOK_RET=$?
  if [[ $PLAYBOOK_RET == 0 ]]; then
    echo "Playbook $PLAYBOOK reported success for $TARGET_HOST_FULL"
    echo ""
  else
    echo "Playbook $PLAYBOOK reported error $PLAYBOOK_RET for $TARGET_HOST_FULL, stopping."
    echo ""
    exit $PLAYBOOK_RET
  fi

} 

The deployment lock checks to see if the lock file exists, if it does it means another process is running so wait. If not it creates a file and writes a random number to it and then reads it back. If it gets a the same number then it means we can continue, if it gets a different number then it takes it as a failed lock attempt and waits until the file no longer exists and tries again. I first used this technique with a MS-DOS batch file over 30 years for a similar process control problem.


DeployLock () {
# Obtain a file-based lock on deployments to prevent any others running

  local LOCK_TOKEN
  local LOCK_CHECK
  local LOCK_CONFIRMED=0

  while [[ $LOCK_CONFIRMED == 0 ]]; do

    if [[ -f $LOCK_FILE ]] ; then
      echo "Deployment lock denied, waiting to proceed."

      sleep 60s
      continue
  
    fi

    # Obtain lock
    LOCK_TOKEN=$RANDOM
  
    echo "$LOCK_TOKEN" > $LOCK_FILE
    echo "Deploy lock file for Ubuntu 24.04" >> $LOCK_FILE
    echo "Created $(date)" >> $LOCK_FILE
 
    # Check we got it
    read -r LOCK_CHECK < $LOCK_FILE

    if [[ $LOCK_CHECK == $LOCK_TOKEN ]]; then
      LOCK_CONFIRMED=1
      echo "Deployment lock confirmed, proceeding."
 
    else
      echo "Deployment lock stolen, waiting to proceed."
      continue
    fi

  done 

}


DeployUnlock () {
# Release the deployment lock and allow others to run

  rm $LOCK_FILE

}

Each playbook we need to execute is called from by the appropriate run function.


#######################################
# Main execution
#

DeployLock

RunPlaybookDeploy ubuntu24-10.yaml 
RunPlaybookConnectSSH ubuntu24-15.yaml $TARGET_BUILD_SSH_USER $TARGET_BUILD_SSH_KEY "--extra-vars ovf_hostname=$OVF_HOSTNAME"

DeployUnlock

RunPlaybookSSH ubuntu24-20.yaml $TARGET_BUILD_SSH_USER $TARGET_BUILD_SSH_KEY 
RunPlaybookSSH ubuntu24-22.yaml $TARGET_BUILD_SSH_USER $TARGET_BUILD_SSH_KEY 

# Switch to Admin key!
RunPlaybookSSH ubuntu24-30.yaml $TARGET_ADMIN_SSH_USER $TARGET_ADMIN_SSH_KEY
RunPlaybookSSH ubuntu24-38.yaml $TARGET_ADMIN_SSH_USER $TARGET_ADMIN_SSH_KEY

echo ""
echo "Ubuntu deploy complete."
echo ""

Although this is now in active use in my GeekLab it's not the final version of the as there's a few things that I'm not happy with and could be done better, but for now it works well enough and that is the important thing. I'll update this article with new versions when (if?) they're ready.

On the todo list are:

  • Combine hostname and domain into single parameter and let the script separate them as needed. This is purely a usability thing.
  • Include a parameter for restart so that if a playbook fails I can fix the error and easily rerun that playbook and continue the deployment

The bash scripts take a hostname and domain as input parameters and are intended to build a single VM at a time even though Ansible is quite capable of running a playbook against several VMs at once. While this scenario is unlikely in my Geeklab I have a more fundamental limitation with using OVF templates in that when the newly imported VM is first booted it has the hostname of the template VM it was created from. If I deploy two VMs with the same template at the same time I will have two hosts on the network with the same name. This will then cause issues with DNS and hostname resolution so when Ansible connects to start configuration it won't know which one it's connected to.

To prevent this I use a lock file so the deploy script will check if any other VM for that particular template is currently being deployed and then when it starts deployment it will write a lock to prevent any other deployments of that template. Once the OVF template has been deployed and the first playbook has renamed and rebooted it the lock is released to allow any other deployments to proceed.

This is not fool-proof as it won't block other Deployers and it will also delay deployments into other domains from the same deployer unnecessarily but it's better than nothing.  Of course if I could apply a rename command on first boot I probably wouldn't need this.

It should also be obvious that this script can only handle the deployment of a single VM at a time. While Ansible playbooks can be run against dozens of instances in parallel this script would need significant to enable that. While it would be an interesting exercise that's not something I have any need of in my little GeekLap. At least not at the moment.

cleardeploylock.sh

This is just as simple script to clear the deploy lock file should the deployment crash so badly that ubuntu24-deploy.sh file doen't remove it. I've not had to use since I got the deployer scripts working but it's worth keeping just in case. You need to make sure the LOCK_FILE is the same as in the ubuntu24-deploy.sh

#!/bin/bash
# Clear the deployment lock

LOCK_FILE=/tmp/deploylock-ubuntu2404.txt

DeployUnlock () {
# Relase the deployment lock and allow others to run

  rm $LOCK_FILE

}

DeployUnlock

It would probably be a good idea to either make the ubuntu24-deploy.sh have a manual unlock feature, or move the LOCK_FILE parameter into the ubuntu24.conf and then source that so it only needs to be specified once. One for the to-do list.