In this step we set prepare a directory for our Ansible playbooks and create some bash scripts that we will use to trigger and control the playbooks as they run against our target VM.
Prepare Playbook Directory
All of the Ansible playbook and roles, bash scripts and other configuration files are going to be placed into a dedicated directory at ~/Projects/ansible/playbooks/nextcloud in my Ansible control host.
~/Projects
ansible
control
inventory
playbooks
nextcloud
One thing I do know for certain is I will be reusing some roles I've created previously which will take configuration parameters and this playbook will also need some parameters of its own so we will need two subdirectories under nextcloud: roles and vars.
Ansible Configuration
We want our Nextcloud playbook to look for any roles in its roles subdirectory, not a central location. To set this we need to create an ansible.cfg file in our nextcloud directory to set the roles_path option.
Filename: ansible.cfg
[defaults]roles_path = ./roles
Git Ignore
If you're using git as source control for your playbook then we can exclude the files from the imported roles from our playbook repository since they're going to installed from another git repository. All file paths are relative to the location of the .gitignore file. Create the .gitignore file in our nextcloud directory.
Filename: .gitignore
# GIT ignore file.vscode
/roles/*!/roles/requirements.yaml!/roles/local_*
This excludes the .vscode directory that Visual Studio code creates (your editor may need its own version), it also excludes all the files in the roles directory, except for the requirements.yaml and any roles with a directory name that starts with local_ as these roles are created explicitly for this playbook so we do want those under source control.
Update the Ansible Inventory
Before we can do anything with Ansible we need to make sure the hosts it'll be working with are available in the Ansible Inventory that you will use with these playbooks.
In our example inventory I defined three development hosts, we'll take the first one for the rest of these articles - svu-ncdeploy-1 - which was defined in the inventory/100-dev.yaml file.
dev:
vars:
[...]
children:
nextcloud_dev:
hosts:
svu-ncdeploy-1.sandpit.example.com:
This is not the actual hostname of our freshly deployed VM, but it is the name it will become. There's a little trick we're going to use to make this work.
Create the launcher scripts
There are a lot of different ways you can launch an Ansible Playbook, some of which get very complicated with uploading parameters via spreadsheets, web portals or configuration management systems and able to configure and reconfigure hundreds of hosts at the same time. I'm keeping it simple since I'm quite happy to do this from a terminal screen and for deployments I will only be working on a single VM at a time.
We need to launch the Ansible Playbook with various parameters and while we could type all this on the command line, putting in a script will simplify it and reduce the opportunities for error. There's several steps in the script and it's tailored around how we structured our Ansible directory.
~/Projects
ansible
control
inventory
playbooks
nextcloud
.gitignore
ansible.cfg
roles
vars
All of our scripts will go in the ~/Projects/ansible/playbooks/nextcloud directory.
Inventory Location
This small bash script can be used as a standalone script to set the path to the inventory, and is also used by the main launcher script for the same purpose. I have a second one called ansible-env-live.sh that does exactly the same job except it uses the live inventory directory.
Filename: ansible-env-dev.sh
#!/bin/bashecho "Setting Ansible DEV environment for new hosts processing"# echo "Make sure you did: source ./ansible-env-dev.sh else it won't work"export ANSIBLE_INVENTORY=../../inventory
This sets an environment variable called ANSIBLE_INVENTORY which contains the path to the inventory directory (see Ansible Inventory) we're going to be using with these playbooks.
Role & Collections Updater
In the first two playbooks I make use of some roles I created for the newhost playbooks. And at some point I will probably break up these playbooks into roles to make at least part of them reuseable elsewhere. While I could have the playbooks trigger an update to the latest roles each time it's run that gets slow so I use a separate script to trigger the update manually.
Filename: refresh-roles.sh
#!/bin/bashecho "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
This script simply calls ansible-galaxy to install all the roles in the requirements.yaml and to refresh them if needed. We'll create the requirements.yaml later. I should probably add an option to install / update the collections too.
Playbook Launcher
This is the main launcher script that we'll build up in stages. Its job is to set the appropriate environment variables and then call each playbook in sequence. We'll be creating playbooks in the next article so consider this a spoiler.
Filename: nextcloud.sh
!/bin/bashecho "Running Ansible Playbooks to prepare a new Nextcloud installation."echo "Please provide localadmin password when prompted"echo ""echo "Setting environment..."
OVF_HOSTNAME="u2004nc-1.sandpit.example.com"PING_RET=255TARGET_HOST=""
source ./ansible-env-dev.sh export ANSIBLE_HOST_KEY_CHECKING=Falseexport ANSIBLE_VAULT_PASSWORD_FILE=../../control/vault-pass
Our VM template set the hostname to u2004nc-1 for all VMs created from it. This first section sets OVF_HOSTNAME to the fully-qualified hostname of our newly deployed VM, which in my case is the sandpit.example.com domain. To be honest this needs reworking so the domain is not hard-coded into the script.
It then calls ansible-env-dev.sh to set the path to the inventory and sets another environment variable ANSIBLE_HOST_KEY_CHECKING to stop ansible checking the SSH key of the deployed VM because we're going to change it anyway.
The last environment variable ANSIBLE_VAULT_PASSWORD_FILE sets the location of a file with the password to the ansible vault we use to hold some other credentials. The control directory is not in a git repository and the file is only accessible to users that need to run the playbook.
if [[ -z $1 ]]; then echo "" echo "Sorry, you need to specify fully-qualified target host name(s)" exitelse TARGET_HOST=$1 ANSIBLE_TARGET="target=$TARGET_HOST"fi
This just checks a target host has been given as a parameter and if given puts in the TARGET_HOST variable and also builds a fragment of the ansible command as ANSIBLE_TARGET.
# Placeholder for RunPlaybookSSH ()
This is a placeholder for something we'll add for the remaining playbooks but don't need just yet.
echo "Running nextcloud1.yaml for $TARGET_HOST"
ansible-playbook -v -k -K -u install_user nextcloud1.yaml --extra-vars ansible_host=$OVF_HOSTNAME --extra-vars $ANSIBLE_TARGET
PLAYBOOK_OK=$?if [[ $PLAYBOOK_OK == 0 ]]; then echo "Playbook nextcloud1 reported success for $TARGET_HOST"else echo "Playbook nextcloud1 reported error $PLAYBOOK_OK for $TARGET_HOST, stopping." exitfi
This will launch our first playbook nextcloud1.yaml (once we've created it in the next article) and then check if it worked, reporting success and then continuing, or reporting failure and then stopping the script.
The parameters for ansible-playbook come from both the command line and the environment variables we set earlier. The -v specifies verbose mode which can help find the reason why any failures occur. As we don't have any SSH keys on the target VM at this point we set -k -K to tell it to prompt for the connection password and also the become password for privileged actions. The next parameter -u install_user specifies we want to connect to the target host as the install_user account that was set in VM template.
We then set a pair of --extra-vars variables. With the first one, which sets ansible_host, we're telling it use a specific hostname for the SSH connection instead of the target hostname. This evaluates to u2004nc-1.sandpit.example.com which we set at the start of our script in OVF_HOSTNAME. The second parameter specifies the target hostname, which we have already defined in the inventory. This would normally be the same name that would be used for the SSH connection but at this point it only exists in the inventory and isn't known to our new VM or DNS.
# Need to pause here until target host becomes available
while [ $PING_RET -gt 0 ]; do ping -c 3 -i 10 $TARGET_HOST PING_RET=$? echo -e "$(date): Got $PING_RET, waiting another minute for $1" sleep 60sdone
Once our first playbook has run it triggers a reboot of the target VM that can take a few minutes so we want to hold here until it become available again. When it restart it will have been renamed from u2004-nc-1.sandpit.example.com to the target name we chose (svu-ncdeploy-1.sandpit.example.com in this example) and will have a new IP address too.
As we use hostnames to connect to the target system this script is dependent on a properly functioning DNS. If you end up having to rerun the deployment, or you're running multiple deployments in quick succession and you have DNS caching it can cause problems if the Ansible control host you're running the script on uses old cached addresses for your target VMt. This was an issue during development when various things broke but I've not seen any issues since.
For the second and subsequent playbooks we'll add an extra section to the end of this script.
Generate SSH Keys and Certificate for the Ansible User
Although we don't need to use these until the 2nd playbook runs, we need to configure part of this in the host-ssh-server role used by Playbook 1 - First Contact.
The ansible user we create in each target system in our first playbook is extremely powerful. It can become root without any further password prompt and then do anything. We will protect the target system by only allowing SSH authentication via keys and locking the ansible user, and we can use client and network firewalls to restrict the hosts that can connect to it via SSH for greater security if we need to.
For the ansible control node we still need to provide an SSH key and this introduces another problem. The usual approach is to have the private key on the control node and install the public key on each target system, and this is described as an option in the first two playbooks. It's simple and it works.
But if the private key should become compromised you need to recreate the key pair and then get into every system and replace the public key. You should really do this on a regular schedule too, which can get very messy especially in a lab environment when hosts are not always running.
To get around this I'm using SSH User Certificates. This means I don't need to maintain a public key for the ansible user in each target system, the certificate is time limited too which helps limit the opportunity for mischief if something happens to it. There is even support for a Certificate Revocation List to make blocking a compromised certificate easier.
A full write-up of the process to create and run an internal SSH Certificate Authority is on the to-do list (I'm presuming that commercial offerings are out of budget for the typical GeekLab).
Now is a good time to generate an SSH key pair for your ansible user if you don't have one already. The keys should be placed in the ansible/control directory and for the private key the permissions should be to 0600 so you (or the user you'll run the playbooks as) are the only user with access.
And if you already have an SSH User CA running then sign the public key of your ansible user and also get the public key of your User CA ready too.
And since the host-ssh-server role generates signed SSH host keys you'll need a separate SSH key pair for that feature if you want to use it.
Recap
We now have the foundations for our Ansible automation in place and the only thing we need now are the Ansible playbooks themselves.
~/Projects
ansible
control
ansible
ansible.pub
ansible-cert.pub
inventory
[inventory files]
playbooks
nextcloud
.gitignore
ansible.cfg
ansible-env-dev.sh
refresh-roles.sh
nextcloud.sh
roles
vars
To run our this playbook against our test VM we will use the nextcloud.sh bash script with the name of the VM we want it to apply to. E.g.
cd ~/Projects/ansible/playbooks/nextcloud
./nextcloud1.sh svu-ncdeploy-1.sandpit.example.com
But of course since we haven't created our playbook yet it's not going to work just yet. I guess we'd better started on that next.