This first playbook renames the target VM from the default in our OVF template then applies some initial Linux configuration so that it's ready for the subsequent playbooks
Automation Overview
If you refer back to the Automation Approach I broke the process for deploying a Nextcloud VM down into six steps:
- Create a virtual machine with the operating system installed and ready for Ansible to start configuration ✅
- Ansible playbook for initial OS configuration to prepare for the main automation execution.
- Ansible playbook to complete OS configuration and install standard utilities and applications
- Ansible playbook to configure Nextcloud-specific pre-requisites such as filesystems, PHP and MariaDB
- Ansible playbook to create the database and deploy Nextcloud itself
- Ansible playbook to do the initial configuration of Nextcloud
In this step we're going to take the VM we deployed from an OVF template in VM Template Deployment and complete some post-deployment steps so the remaining playbooks can be applied.
If you're following along then ensure you have an Ubuntu VM created according the to the template created in VM Template Creation part 1 through to Part 3. Once the VM is ready, it's probably worth creating a snapshot in its initial state so if something interesting happens you can quickly roll it back and try again.
Playbook Requirements
A freshly deployed VM from our OVF Template has a standard hostname which we need to change and then complete some further steps that are hostname dependent. This playbook should do the absolute minimum necessary to allow the remaining playbooks to run without having to prompt for credentials by using the ansible user with an SSH certificate.
This playbook will:
- Apply the correct hostname
- Trigger the regeneration of the machineid since I left that in the original template. Oops.
- Set the fully-qualified hostname
- Configure OpenSSH server with a signed host certificate and to accept signed user certificates too
- Create a user for subsequent ansible playbooks to use
For this playbook it is acceptable for it to prompt for a credentials since we're starting it from a bash script. And that that's how it's predecessor playbook worked too since it had to work with manually deployed VMs. Of course, as this is using an OVF template it means we have other which could allow us automate even this initial login but that's for a future version.
Note: As the template creates VMs with a hard-coded hostname of u2004nc-1 only one can be running at a time until this first playbook has been successfully applied.
Ansible Requirements File
Note: Until I sort out making these roles publicly available (probably via github or gitlab) you don't need this file unless of course you already have your own set of default roles to apply.
As an interim measure details of these roles are available in these links: host-fqdn host-ssh-server host-adduser
Ansible encourages you to package tasks into reuseable components which it calls roles. So while setting the hosts fully-qualified domain name is not a big deal, configuring OpenSSH with signed host keys and enabling user certificates, or deploying and configuring the Bacula client is a more complex task and something I will need to do any playbook involved in initial configuration of Linux VMs in my GeekLab.
As the first two playbooks for our Nextcloud deployment automation are based on my existing newhost playbooks, I can reuse the roles I created for newhost which are tasks 3 to 7 on the playbook requirements list.
While I could copy/paste everything into each playbook it soon become a mess, especially if I need to enhance a role or fix bugs. Ansible provides an automated way to manage and update roles, the requirements file, and we can make use of git for this.
In the GeekLab I have an Ubuntu VM which acts as a simple git server using SSH. Using the refresh-roles.sh script (see Playbook Preparation) any authorised user can connect to the git server, referred to here as tiger.example.com and get the required version, typically the latest, of any role I have shared on there. This can also work over HTTP/S as well as to GitLab instances or services such as GitHub.
So if I need to make an update to the host-ssh-server role, any playbook that relies on that can quickly get the update with just a single command. Or if I want to switch to a development version of a role for a specific playbook, I can.
Setting up the git server and sharing the roles is beyond the scope of this article, but it is on my to-do list and I will link to it when it's ready.
Filename: roles/requirements.yaml
--- # Required roles# Make sure .gitignore set to exclude these from the playbook
############################# nextcloud1.yaml
roles:- name: host-fqdn scm: git src: tiger.example.com:/srv/git/ansible/roles/host-fqdn.git version: master
- name: host-ssh-server scm: git src: tiger.example.com:/srv/git/ansible/roles/host-ssh-srv.git version: dev
- name: host-adduser scm: git src: tiger.example.com:/srv/git/ansible/roles/host-adduser.git version: master
############################# nextcloud2.yaml
# Two more roles will be added here for playbook 2
# And add collections too. Need explicit call from ansible-galaxy to install.
collections: - name: community.general - name: community.crypto
# Other applications needed# OS: sshpass
...
Once you have created the requirements file you can run the refresh-roles.sh script and Ansible will fetch the specified version of each role and deploy it into the roles directory for you.
As the script mentions you'll need to run the ansible-galaxy collections command at least once to also install the three collections listed here that are relied by these roles. Periodically updating the collection (and Ansible itself) is also a good idea.
And you'll also need sshpass installed on the Ansible host so it can properly prompt for SSH passwords for the first playbook. That can't be included in the playbook as it's a bit of a chicken/egg situation.
Variables: newhost
This playbook is based on my newhost playbook which has some variables defined for use with the role to create and sign an SSH host key and also deploy an SSH CA certificate to validate user certificates so we need to add them to this playbook too.
Filename: vars/config-newhost.yaml
--- # Ansible Vars# Custom variables for Ansible newhost playbooks
config_ssh_hostca_key: "../../control/host-ca"config_ssh_userca_cert: "user-ca.pub"
config_ssh_hostca_cred: "{{ vault_ssh_hostca_cred }}"
...
The variables define the location of a file (host-ca) in the control directory that contains the OpenSSH host signing key, the name of the OpenSSH CA certificate to use for enabling SSH user certificates and the credential to allow the use of the OpenSSH host signing key which is held in the vault_ssh_hostca_cred variable in a separate variables file.
Filename: vars/vault-newhost.yaml
--- # Ansible Vars# Vault for secret variables
vault_ssh_hostca_cred: MyTopSecretSigningKeyPassword
...
The vault-newhost.yaml file should be encrypted using ansible-vault as soon as you've created it, and certainly before it's checked in to git, and the password put into the control/vault-pass file which is specified in the nextcloud.sh bash script ANSIBLE_VAULT_PASSWORD_FILE parameter. Note that vault_ssh_hostca_cred is the password for the SSH key, not the password used to encrypt the vault file itself.
Playbook: New Nextcloud Host - First Contact
This is based on my newhost playbook (which I will write up one day) and its job is to do just enough configuration to get the host ready for subsequent playbooks without needing any further human intervention.
Filename: nextcloud1.yaml
---# Ansible Playbook
# New Nextcloud host setup# Stage 1: Initial OS configuration## For this initial connection we use password authentication# ansible_host must be set to the initial hostname so we can connect to it to perform the rename.## setenv ANSIBLE_HOST_KEY_CHECKING=False to run this, and add key to known hosts.
- name: New Nextcloud Host - First contact hosts: "{{ target }}"
vars_files: - vars/vault-newhost.yaml - vars/config-newhost.yaml - vars/vm-template.yaml
This first section determines which host to run on using the target hostname we passed in from the launcher script as an --extra-vars parameter. We also include the two variables files we created above, plus one more we'll need for this playbook.
roles:
- role: local_host-rename
- role: local_host-id
Ansible executes roles before tasks in a playbook, so we needed to move the first tasks into roles. The first role local_host-rename checks we're really connecting to a new VM deployment from our OVF template and will fail the play if it isn't so it must be the very first thing we do. Since we need it to trigger a reboot at the end of the playbook we can't use a pre-tasks section either. The second role local_host-id regenerate the machineid. These two roles are explored in more detail below
- role: host-fqdn
- 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-adduser vars: local_ansible_user: ansible when: "'ad_domain' not in group_names"
These roles are downloaded by the refresh-roles.sh script we created earlier as specified by the requirements.yaml we created above. If you're using the host-ssh-server role don't forget to provide your SSH keys and credentials to it.
handlers: # Changing hostname & IP means it won't reconnect. - name: Reboot host become: true ignore_errors: true ansible.builtin.reboot: reboot_timeout: 60
...
This final section triggers a reboot of the host if any of the preceding roles have requested it via a notify: Reboot host call. Since we change the name of the host and the machineid which means it should also get a new IP address after the reboot there's no way for the playbook to reconnect so we set ignore_errors to true so that when ansible.builtin.reboot fails to reconnect it doesn't cause the playbook to fail.
The launcher script will trigger the next playbook to run using the new hostname, and that's covered in the next article in this series.
Role: local_host-rename
This role renames the host to its correct hostname. There is a chance (and I know 'cos it happened to me) that thanks to DNS caches your Ansible control node could retain an old IP address for the hostname of freshly deployed VM from our OVF template, which means there's a risk we might connect to a different host which would be bad so we need to handle that situation. Automatically disabling the initial connection user during one of the later playbooks would reduce this risk further but you'd want to create at least one other account with sudo rights as an emergency access user for troubleshooting.
Filename: roles/local_host-rename/tasks/main.yaml
---# Ansible Role Tasks# Ubuntu 20.04 LTS# Rename target host if it matches then initial name set in the OVF template.# Abort the play if not so we don't muck up a real host (i.e. DNS / name cache is causing problems )
- 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
...
The first task simply checks if the host we're running on has the correct hostname for a newly deployed VM from our OVF template which we specify in var/vm-template.yaml. If it's not then we display a warning message and fail the playbook which in turn causes our launcher script to abort too and should mean no harm is done.
The second task can then go ahead and rename the host as desired and then trigger a reboot at the end of the playbook.
Role: local_host-id
The /etc/machineid file is used in the DHCP process to request an IP address and each host should have a unique value. This role causes it to be regenerated if the host is still using the one from our VM template.
Filename: roles/local_host-id/tasks/main.yaml
---# Ansible Role Tasks# Ubuntu 20.04 LTS# Reset machine-id if still value as original host template
- name: Check /etc/machine-id exists ansible.builtin.stat: path: /etc/machine-id register: machineid_exists
- name: Get /etc/machine-id ansible.builtin.shell: cmd: cat /etc/machine-id register: machineid when: machineid_exists.stat.exists
- name: Show machine-id ansible.builtin.debug: msg: "Machine ID is {{ machineid }}"
- name: Remove /etc/machine-id become: true ansible.builtin.file: path: /etc/machine-id state: absent when: machineid.stdout | default('Not Exist') == ovf_machineid notify: Reboot host
- name: Create empty /etc/machine-id become: true ansible.builtin.file: path: /etc/machine-id owner: root group: root mode: '0444' state: touch
...
The first three tasks check if the /etc/machineid file exists and then reads it's contents which should be just the machineid. It then checks if it matches the machineid of our VM template (which is held in vars/vm-template.yaml) and if it does it deletes the machine-id file and triggers a reboot at the end of the playbook.
The last task creates an empty /etc/machineid file so that after the reboot Linux will regenerate a new machineid automatically as it won't do this if the file doesn't exist.
A lesson for version 2 of this process will be to remove the /etc/machineid file from the template VM before creating the template so each deployment will always have a unique machineid.
Variables: vm-template
The local_host-rename and local_host-id roles need to know the original hostname and machineid set in the VM template as part of checks to make sure we're only working on a newly created VM based on our template. By using a variable file we can update the name and macineid to work with new templates without having to edit the playbook, or even override the values via an --extra-vars parameter on to ansible-playbook.
Filename: vars/vm-template.yaml
---# Ansible Vars# Custom variables for OVF customisation
ovf_hostname: u2004nc-1ovf_machineid: 0acdb62456fe47c99e2644f5c5afc84e
...
These must match the hostname and contents of the /etc/machineid file in the VM template. Your template VM will have at least a different machineid so your value for ovf_machineid will be different too.
Test
By this point we have the foundations for our Ansible automation in place and the first playbook is ready for testing. It's worth taking a snapshot of the test VM at this point so that if it doesn't work as planned you can quickly revert it back and try again. Ansible recommends that playbooks are idempotent, you should be able to run them repeatedly and still get the same final result, and this playbook is not as make permanent changes to the Linux configuration and deliberately don't allow this playbook to run if the start condition is not as we're expecting.
The file structure should now look something like this:
~/Projects
ansible
control
ansible
ansible.pub
ansible-cert.pub
host-ca
vault-pass
inventory
[inventory files]
playbooks
nextcloud
.gitignore
ansible.cfg
ansible-env-dev.sh
refresh-roles.sh
nextcloud.sh
nextcloud1.yaml
roles
requirements.yaml
local_host-rename
tasks
main.yaml
local_host-id
tasks
main.yaml
[other downloaded roles]
vars
config-nextcloud.yaml
vault-nextcloud.yaml
vm-template.yaml
If we had the other roles accessible we'd need to install them and the two collections. But since we don't right now we can skip this bit while you apply the manual workarounds I've mentioned.
cd ~/Projects/ansible/playbooks/nextcloud
./refresh-roles.sh
ansible-galaxy collection install -r ./roles/requirements.yaml
You will need to repeat this again if you set up the playbook on another host or even in another directory. And of course if changes are made to the roles you'll need to run refresh-roles.sh to get them.
To run our this playbook against our test VM we use the nextcloud.sh bash script with the name of the VM we want it to apply to.
cd ~/Projects/ansible/playbooks/nextcloud
./nextcloud1.sh svu-ncdeploy-1.sandpit.example.com
And after a few minutes the playbook will complete, the target VM will reboot and when it returns it will have been renamed to svu-ncdeploy-1 and be ready for the next stage of configuration, which will be covered in the next article.
Review and footnotes
The local_host-rename and local_host-id roles are the bare minimum and are not (yet) fully specified roles but they do work.
This playbook may not be optimal, but then given the constraints of the GeekLab it's good enough and that's really what counts.
This playbook was based on the first of my newhost playbooks and the roles I created as part of that, and the write-up of that is on my article backlog. It would add too much to this article to go into them here and yes, I know it makes this article a bit harder to follow, especially if you're using it as a tutorial. I also intend to put all the roles and playbooks onto an easy location for download, possibly GitLab or GitHub or maybe just a zip download but there's a few things I need to work through first - and probably a couple of articles will come from that process as well.
As mentioned in previous articles, since there's already a degree of dependency between the OVF template and these playbooks it might be better if I created the ansible user in the template too and I really should have fixed up the machineid to save a role here. I could have also pre-configured some of the SSH configuration although that would have mean breaking up the role as I would still have to the hostname-specific parts in this playbook.