Two additional playbooks are needed to handle the OVF template deployment and applying the correct hostname and the original playbooks have been reorganised. The playbooks have also been simplified as some of the steps they performed have been baked into the template.

With these playbooks our Deployer is ready for use.

Ansible Configuration

We've already touched on the Inventory which is required for any Ansible playbooks in the Preparation section, and the ancible.cfg which is used to set the location for roles to be local to the playbooks.

My plan is to largely reuse the playbooks for each deployment variation I need so I've created a structure that I hope will be flexible and if not future-proof at least future-tolerant. 

The idea is that playbooks should deliver major steps in a deployment and it should be possible to restart them if an error occurs to save having to do everything from scratch. This also means I can easily add a pause between playbooks if I needed to make some manual changes.

The playbooks themselves are named for the OS being deployed and then split into three groups. So taking these Ubuntu 24.04 LTS playbooks I've used ubuntu24 as the first part of the name with two digits to separate out the playbooks as follows:

  • 00 to 09 : Pre-deployment actions on the hosting environment. Not currently used.
  • 10 to 19 : OVF deployment and changes to the deployed VM to make it ready for configuration. e.g: rename to correct hostname
  • 20 to 29 : OS configuration, configuration of other tools and utilities included in the template
  • 30 to 39 : Deployment of additional tooling and utilities for OS management, e.g. backup
  • 40 onwards : Not used (yet...)

I've also left gaps between the playbook numbers to make it easier to add intermediaries without having to renumber. So hopefully in all variations the Ubuntu deployments ubuntu24-22.yaml will always be the one that handles domain join, but if I needed to enable a specific logging configuration on selected VMs I might add a ubuntu24-24.yaml to handle that.

While this has no impact on Ansible itself as playbooks are always called explicity, I'm hoping this will make it easier for me manage as it evolves. Time will tell if this helps or is just over-thinking a non-problem.

 

Role requirements.xml

Another of the ways that Ansible encourages the reuse of automation components, and arguably the most powerful, is roles. A role is all the tasks, variables, files and templates need to automate something. You can reuse roles within your own playbooks and also share them with others, and also make use of other peoples roles too. Most of these roles have been adopted from the previous automations with only a few minor adjustments to work here too - with the exception of my bacula-client role which had a substantial update to simplify and I ended up with a dedicated branch for this template.

To make use of roles you need install them and then declare in your playbook. The requirements.xml file lists all the roles you want to use together with details on where to obtain them from. The refresh-roles.sh script in the Deployment - Bash scripts calls the ansible-galaxy tool to use this list to install all the roles we need into the roles directory under our playbooks.

 

--- # Required roles
# Make sure .gitignore set to exclude these from the playbook

roles:
  - name: host-fqdn
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/host-fqdn.git
    version: master

  - name: host-time
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/host-time.git
    version: master

  - name: host-ssh-server
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/host-ssh-srv.git
    version: master

  - name: host-ssh-client
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/host-ssh-client.git
    version: master

  - name: host-joindomain
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/host-joindomain.git
    version: master

  - name: host-adduser
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/host-adduser.git
    version: master

  - name: apcupsd
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/apcupsd.git
    version: master

  - name: bacula-client
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/bacula-client.git
    version: template-u2404
 
  - name: host-tls
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/host-tls.git
    version: master

  - name: gitdeploy
    scm: git
    src: git-host.example.com:/srv/git/ansible/roles/gitdeploy.git
    version: master

collections:
  - name: community.general
  - name: community.crypto

# Example src paths for local development
#   localhost:~/Projects/ansible-roles/apcupsd
#   git+file:///home/user/Projects/ansible-roles/host-fqdn
...

The src parameter for all of these roles reference an internal server so I've faked that for now. At some point I plan to make them publicly available somewhere if anyone is crazy enough to trust my code directly. 

Playbook ubuntu24-10.yaml

This playbook creates a new VM using the OVFtool to import the selected template.

It is called using the special RunPlaybookDeploy function of the deploy script to pass in the ESXi credentials via the esx-deploy.yaml file (vaulted of course!) with all the remaining parameters provided via the inventory, ideally based on group memberships for all but the template itself.

 

--- # Ansible Playbook

# New Ubuntu 24.04 host setup
#   Stage 1: OVF Deployment
#   
# This runs against the control node so does not require a user on the target hosts which don't exist yet.
#   It also needs info about the control node passed in as extra-vars maintained in the control directory
#   The inventory also needs to provide:
#     Source template for the VM.
#     Target ESX host for the VM and its credentials, using vault where appropriate.
#
# ESXi authentication is passed on the command line which is not brilliant.
#


- name: Deploy OVF using VMware OVFtool
  hosts: "{{ target }}"
  gather_facts: no

   
  tasks:

  - name: assemble command
    ansible.builtin.debug:
      msg:
      - "Target: {{ target }}"
      - "tool location: {{ ovf_tool_location }} "
      - "ESXi host: {{ esx_host }}"
      - "ESXi User: {{ esx_user }}"
      - "ESXi Pass: ************"
      - "ESXi Network: {{ esx_network }}"
      - "ESXi Datastore: {{ esx_datastore }}"
      - "ESXi Name: {{ config_landscape_tier}}_{{ inventory_hostname_short }}"
      - "OVF Source: {{ esx_ovf_base}}/{{ esx_ovf_source }}"

      
  - name: import OVF
    delegate_to: localhost
    ansible.builtin.command:
      argv:
      - "{{ ovf_tool_location }}"
      - --datastore={{ esx_datastore }}
      - --name={{ config_landscape_tier }}_{{ inventory_hostname_short }}
      - --network={{ esx_network }}
      - --diskMode=thin
      - --machineOutput

      - --powerOn
      - "{{ esx_ovf_base }}/{{ esx_ovf_source }}"
      - vi://{{ esx_user }}:{{ esx_pass }}@{{ esx_host }}

...

This is executed on the control node via the delegate_to directive since that is where the OVFtool is located. And since we don't actually have a target VM until a few minutes after this play has finished I disable the gather facts process for the entire playbook since there's nothing to gather. The RunPlaybookDeploy function also waits for the VM to respond to ping commands after the playbook has finished before allowing processing to continue just so we're sure we have a VM to continue working with.

The OFVtool parameters were proven in a bash script first. The tool is capable of a lot more such as changing vCPU and RAM during import, the only two optional settings I've used is defaulting the disks to thin provisioning (it's easy to convert to thick later if needed) and the more automation-friendlyl machineOutput. 

Playbook ubuntu24-15.yaml

This playbook completes the template deployment phase and renames our newly deployed OVF template to the required hostname for the VM.

It is called using the RunPlaybookConnectSSH function of the deployer script as we need to connect to it using the special ansible connection variable ansible_host set to the initial hostname defined in the OVF template since that's the name in DNS for te first boot, but have all the tasks use the inventory_hostname that it will be renamed to so they pick up the correct settings from the inventory.

 

--- # Ansible Playbook

# New Ubuntu 24.04 host setup
#   Stage 1: OVF Deployment
#   
# This checks it's connected to the newly imported VM, renames it and then triggers a reboot.
# VMs shouldn't change IP any more but may happen. We are at the mercy of DHCP & DNS for this to be successful.
#


- name: Complete OVF deployment
  hosts: "{{ target }}"


  tasks:

  - name: Show actual hostname
    ansible.builtin.debug:
      msg: This host is currently named {{ ansible_hostname }} and I am expecting {{ ovf_hostname }}
      
  - name: Abort if unexpected hostname
    ansible.builtin.fail:
      msg: This VM is supposed to be {{ ovf_hostname }}. It appears to be {{ ansible_hostname }} so aborting the play.
    when: ansible_hostname != ovf_hostname

  - name: Rename host
    become: true
    ansible.builtin.hostname:
      name: "{{ inventory_hostname_short }}"
    notify:
    - Reboot host

  handlers:
    # Changing hostname may change IP which means it won't reconnect.
  - name: Reboot host
    become: true
    ignore_errors: true
    ansible.builtin.reboot:
      reboot_timeout: 60

...

The Ubuntu machine_id is set to empty in the template so that it gets regenerated during the first boot. This should mean our VM gets new permanent DHCP identifiers used during address negotiation (as well as a getting a new interface MAC during the import) so that even after a change of hostname it should keep the same IP address it was initially assigned.

Just in case the change of hostname does cause issues the reboot command is configured to continue after 60 seconds even if it can't reconnect to the original IP and we'll let the next playbook connect if it's just being really slow, or timeout and stop the deploy. . This is dependent on the DHCP & DNS configuration between the control node and the new VM.  I've had issues with this on some lab networks and a quick edit of the /etc/hosts file on the control node is all that's required until the DNS1 gets properly configured. Maybe one day I'll find a way to fix up the router internal DNS via automation too.

1 If in doubt, blame DNS. Or the printer. For network printers it's probably DNS too...

Playbook ubuntu24-20.yaml

This playbook applies the customisation of all the base applications and utilities that are part of every Ubuntu VM. They're all included in the OVF template so should not need installation which saves a huge amount of time. Of course it's likely that updates will be needed eventually which will slow things down.

--- # Ansible Playbook

# New Ubuntu 24.04 host setup
#   Stage 2: OS General Configuration
#
# Using the builder key complete OS configuration tasks applicable to all hosts.
#
#

- name: OS Configuration - all hosts
  hosts: "{{ target }}"

  vars_files:
  - vars/vault-newhost.yaml
  - vars/config-newhost.yaml

  roles:

  - role: host-fqdn

  - role: host-time

  - role: host-ssh-server
    vars:
      ssh_hostca_key: "{{ config_ssh_hostca_key }}"
      ssh_hostca_cred: "{{ config_ssh_hostca_cred }}"
      ssh_userca_cert: "{{ config_ssh_userca_cert }}"

  - role: host-ssh-client

  - role: host-tls
    vars:
    - tls_host_requestcert: true

  - role: apcupsd
    when: "'workstation' not in group_names"


  handlers:
  - name: Reboot host
    become: true
    ignore_errors: true
    ansible.builtin.reboot:
      reboot_timeout: 60

...

All of these roles were used in my previous automation and only trivial changes were needed. Some of the original roles have now become redundant as the configuration they deployed is now part of the template and the host-multipath role is no longer needed as it appears the VMware drivers have been fixed so they no longer fill the log with errors about missing UUIDs. A big time saving is from the packages the roles deploy are available in the OVF template so they don't have to do the deployment - unless there's new version released at some point.

  • The host-fqdn role sets the fully-qualified domain name of the host (e.g demo1.sandpit.example.com).
  • The host-time role sets the timeserver address in timesyncd.conf if the host marked as not using DHCP by the network_type set to static in the inventory.
  • The host-ssh-server role configures the SSH server with a host certificate signed by the deployer and also to trust signed user certificates from an internal SSH Certificate Authority.
  • The host-ssh-client role sets some defaults and trust for the SSH certificates when connecting to another internal server.
  • The host-tls role deploys the root certificate for an internal TLS Certificate Authority, generate a Certificate Signing Request for the host and emails a copy to me for processing.
  • The apcupsd role configures the apcupsd service to use the appropriate alert host on its subnet to get the status of the UPS and to shut itself down if the UPS runtime or battery levels are reached - these values are taken from the inventory too.

I still need to document a few of these, which is on my todo list. 

Playbook ubuntu24-22.yaml

Every VM also needs a user for Ansible to connect as. This is either via their domain membership, or if they're not joined to a domain this user needs to be created locally. The Samba components will always be deployed by the role as they're not included in the image.

--- # Ansible Playbook

# New Ubuntu 24.04 host setup
#   Stage 2: OS General Configuration
#
# Using the builder key complete OS configuration as needed for the role of this host.
#
#

- name: OS Configuration - Domain Join
  hosts: "{{ target }}"

  vars_files:
  - vars/vault-newhost.yaml
  - vars/config-newhost.yaml


  roles:

  - role: host-joindomain
    vars:
      ad_admin:  "{{ config_ad_admin_user }}"
      ad_admin_cred: "{{ config_ad_admin_cred }}"
    when: "'ad_domain' in group_names"

# TODO:
#   Handle SambaDC config - maybe post-reboot.

  - role: host-adduser
    vars:
      local_ansible_user: automation-user
    when: "'ad_domain' not in group_names"


  handlers:
    # IF IP changes it may not reconnect.
  - name: Reboot host
    become: true
    ignore_errors: true
    ansible.builtin.reboot:
      reboot_timeout: 60

...

If the target is joined to a Samba/AD domain then it gets rebooted again. The IP address or hostname shouldn't change at this point. Otherwise create the automation user as a local account using the host-adduser role.

Playbook ubuntu24-30.yaml

Finally we start applying optional components (which may still be installed in the OVF template if they're usually deployed). From now on we also execute tasks as the ansible administration user.

--- # Ansible Playbook

# New Ubuntu 24.04 host setup
#   Stage 3: OS configuration cross-system tasks
#
# Using the ansible key complete general OS configuration of this host.
#
#

- name: OS Configuration - Client/Server apps
  hosts: "{{ target }}"

  roles:

  - role: bacula-client
    when: bacula_deploy 

  - role: gitdeploy
    when: bacula_deploy
    vars:    
      git_repo: ssh://git-host.example.com:/srv/git/scripts/bacula.git
      git_version: u24os
      destination: /opt/example.com/bacula

...

The bacula-client role deploys the configuration for the Bacula File Daemon (that's pre-installed in the template) and optionally uploads the client config to the Bacula Director for me as well. This role had a significant rewrite into a template-specific version which made it a lot simpler as it handles the full config itself rather than taking the config created by the Bacula installer and then trying to customise it. 

The call to gitdeploy uses a call to a local git archive command on the Deployer to download the required scripts to the control node which are then sent to to target host and extracted. This means the target host doesn't need direct access to my internal git repos, and the latest version of the script is deployed too. In this case it's the bacula OS snapshot create/release script for backups.

The roles bacula-client and gitdeploy will be covered in separate articles real soon now...

Playbook ubuntu24-38.yaml

The final playbook removes the build user and associated config that was used in the first two sets of playbooks.

--- # Ansible Playbook

# New Ubuntu 24.04 host setup
#   Stage 3: OS configuration cross-system tasks
#
# Remove build artifacts. The final userdel may not work if there are zombie processes
# owned by the build user.
#
#

- name: OS Build Completion
  hosts: "{{ target }}"


  tasks:

  - name: Lock build user
    become: true
    ansible.builtin.user:
      name: ansiblebuilder
      password_lock: true


  - name: Remove build sudoers file
    become: true
    ansible.builtin.file:
      path: /etc/sudoers.d/ansiblebuilder
      state: absent


  - name: Find any remaining ansibuild processes
    shell: "ps -ef | grep ansiblebuilder | awk '{print $2}'"
    register: builder_processes


  - name: Display list processes
    ansible.builtin.debug:
      msg: "Found some running processes: {{ builder_processes.stdout_lines }}"
      

  - name: Wait for ansiblebuilder processes to complete
    wait_for:
      path: "/proc/{{ item }}/status"
      state: absent
      delay: 5
      sleep: 5
      timeout: 300
    with_items: "{{ builder_processes.stdout_lines }}"


  - name: Remove public SSH key
    become: true
    ansible.builtin.file:
      path: /home/ansiblebuilder/.ssh/authorized_keys
      state: absent


  - name: Remove build user
    become: true
    ansible.builtin.user:
      name: ansiblebuilder
      state: absent
      remove: yes

...

This is probably overkill, but I really don't want to leave any build relics behind, especially those which could grant root access to the host later.

With this last playbook in place we now have a completed Deployer for Ubuntu 24.04 LTS using the OVF template we created at the start of this series.

The final step is testing and making sure that it all works (of course it does!) and we can now start deploying ready-to-eat Ubuntu VMs in about 5 minutes. Barely enough time to grab a coffee.