You learn Ansible by practicing, and to practice you need servers you can configure, break and rebuild without fear. In this lesson you will build the Aurora Store lab: three Ubuntu 24.04 virtual machines (web1, web2 and db1) created with Vagrant and VirtualBox, reachable over key-based SSH from your control node. You will also create the aurora-infra/ repository under git version control, where all of the course's automation will live. By the end, you will have exactly the topology we will use in every following module.
Contents
- Lab topology
- Required tools: VirtualBox and Vagrant
- Creating the
aurora-infra/repository with git - Generating an SSH key for the lab
- The Aurora Store Vagrantfile
- Starting and managing the machines
- Checking SSH access manually
~/.ssh/config(optional, but recommended)- Saving your work in git
- Alternatives: Docker containers and cloud machines
- Lab topology
flowchart LR
CN["Control node<br/>(your computer)<br/>Ansible + aurora-infra/"]
subgraph RED["Private network 192.168.56.0/24"]
direction TB
subgraph WS["webservers group"]
W1["web1<br/>192.168.56.11<br/>nginx"]
W2["web2<br/>192.168.56.12<br/>nginx"]
end
subgraph DS["dbservers group"]
D1["db1<br/>192.168.56.21<br/>PostgreSQL"]
end
end
CN -- SSH --> W1
CN -- SSH --> W2
CN -- SSH --> D1
| Machine | IP | Group (future) | Role | RAM | CPU | OS |
|---|---|---|---|---|---|---|
web1 |
192.168.56.11 | webservers |
Web server (nginx) | 1 GB | 1 | Ubuntu 24.04 |
web2 |
192.168.56.12 | webservers |
Web server (nginx) | 1 GB | 1 | Ubuntu 24.04 |
db1 |
192.168.56.21 | dbservers |
Database (PostgreSQL) | 2 GB | 2 | Ubuntu 24.04 |
Notes:
- They will all use the remote user
vagrant, which comes preconfigured with passwordlesssudo. Later in the course you will create a dedicateddeployuser with Ansible. - The
webserversanddbserversgroups don't exist yet: you will define them in the inventory. In lesson 1.5 you will create a minimal one, and in Module 2 ("Inventory Files") you will study it in depth. - In this lesson we won't install nginx or PostgreSQL: Ansible will do that later. The machines stay "clean", just as a provider would hand them over.
You will need about 4 GB of free RAM and about 10-15 GB of disk space.
- Required tools: VirtualBox and Vagrant
- VirtualBox is a free hypervisor: it creates and runs the virtual machines.
- Vagrant is a tool that describes virtual machines in a text file (
Vagrantfile) and creates them reproducibly. It is, in itself, a small example of infrastructure as code.
Installation guidelines:
# Ubuntu/Debian (Linux control node)
sudo apt update
sudo apt install -y virtualbox
# Vagrant: download the official package from HashiCorp's website
# or add their apt repository following their documentation.
# macOS (Intel processor) with Homebrew
brew install --cask virtualbox vagrantCheck the versions:
WSL2 users: VirtualBox and Vagrant must be installed on Windows, not inside WSL2. You can run
vagrantfrom PowerShell in the lab folder and use Ansible from WSL2, connecting to the192.168.56.xIPs. If networking between WSL2 and VirtualBox gives you trouble, see the alternatives in section 10.Macs with Apple Silicon (M1/M2/M3…): VirtualBox has limited support on ARM. Use the container or cloud alternative (section 10), or a compatible Vagrant provider such as VMware Fusion or Parallels with an Ubuntu 24.04 ARM box.
- Creating the
aurora-infra/ repository with git
aurora-infra/ repository with gitEverything you do from now on will live in a single repository. Create it in your home directory:
mkdir -p ~/aurora-infra/lab: creates the project directory and, inside it,lab/, where we will keep theVagrantfile. This separates the lab (the machines) from the automation (inventories, playbooks…), which will go at the root of the repository.git init -b main: initializes a git repository with the main branch namedmain.
If this is the first time you use git on this computer, set your identity (fictitious details in the example):
git config --global user.name "Alex Admin"
git config --global user.email "[email protected]"Create a .gitignore file so that git doesn't store temporary files or secrets:
cat > .gitignore <<'EOF'
# Vagrant internal state (contains private keys and VM data)
lab/.vagrant/
# Ansible temporary files
*.retry
# Editor and system files
*.swp
.DS_Store
EOFlab/.vagrant/: Vagrant stores the machines' state here, and even private keys. It must never be pushed to a repository.*.retry: files that older versions of Ansible generated when a playbook failed.
- Generating an SSH key for the lab
Ansible connects over SSH, and the right way to do so is with public key authentication, not with a password. We will create a key dedicated to the lab:
| Option | Meaning |
|---|---|
-t ed25519 |
Modern, secure and compact key algorithm |
-f ~/.ssh/aurora_ed25519 |
File path. Two files are created: the private key (aurora_ed25519) and the public key (aurora_ed25519.pub) |
-C "..." |
Comment to identify the key |
-N "" |
No passphrase. Acceptable only in a lab; in production use a passphrase and ssh-agent |
Check that both files exist and look at their permissions:
-rw------- 1 student student 411 Nov 26 10:02 /home/student/.ssh/aurora_ed25519
-rw-r--r-- 1 student student 101 Nov 26 10:02 /home/student/.ssh/aurora_ed25519.pubThe private key must have 600 permissions (-rw-------); otherwise, SSH will refuse to use it.
How does the public key get to the servers?
On a regular server you would use ssh-copy-id, which connects once with a password and adds your public key to the remote user's ~/.ssh/authorized_keys:
In our lab we will do it automatically from the Vagrantfile itself (next section), because Vagrant boxes usually disable password-based SSH access. Even so, it's important that you know ssh-copy-id: you will use it with real servers.
- The Aurora Store Vagrantfile
Create the file ~/aurora-infra/lab/Vagrantfile with this content:
# -*- mode: ruby -*-
# Aurora Store lab: web1, web2 (webservers) and db1 (dbservers)
# 1. Public key we will authorize on the machines
PUBKEY_PATH = File.expand_path("~/.ssh/aurora_ed25519.pub")
unless File.exist?(PUBKEY_PATH)
abort "#{PUBKEY_PATH} not found. Generate the key with ssh-keygen before 'vagrant up'."
end
PUBKEY = File.read(PUBKEY_PATH).strip
# 2. Machine definitions
MACHINES = {
"web1" => { ip: "192.168.56.11", memory: 1024, cpus: 1 },
"web2" => { ip: "192.168.56.12", memory: 1024, cpus: 1 },
"db1" => { ip: "192.168.56.21", memory: 2048, cpus: 2 },
}
Vagrant.configure("2") do |config|
# 3. Common base image: Ubuntu 24.04
config.vm.box = "bento/ubuntu-24.04"
config.vm.box_check_update = false
config.vm.synced_folder ".", "/vagrant", disabled: true
# 4. One definition per machine
MACHINES.each do |name, opts|
config.vm.define name do |node|
node.vm.hostname = name
node.vm.network "private_network", ip: opts[:ip]
node.vm.provider "virtualbox" do |vb|
vb.name = "aurora-#{name}"
vb.memory = opts[:memory]
vb.cpus = opts[:cpus]
end
# 5. Authorize our public key for the vagrant user
node.vm.provision "shell", inline: <<-SHELL
install -d -m 700 -o vagrant -g vagrant /home/vagrant/.ssh
touch /home/vagrant/.ssh/authorized_keys
grep -qxF '#{PUBKEY}' /home/vagrant/.ssh/authorized_keys \
|| echo '#{PUBKEY}' >> /home/vagrant/.ssh/authorized_keys
chown vagrant:vagrant /home/vagrant/.ssh/authorized_keys
chmod 600 /home/vagrant/.ssh/authorized_keys
SHELL
end
end
endBlock-by-block explanation (the Vagrantfile is written in Ruby, but you don't need to know Ruby to understand it):
- Public key: the path to
~/.ssh/aurora_ed25519.pubis computed. If it doesn't exist,abortstops Vagrant with a clear message. Its contents are then read into thePUBKEYconstant. MACHINES: a dictionary with each machine's name, IP, memory (MB) and CPUs. If you want to addweb3in the future, one more line is all it takes.- Common configuration:
config.vm.box = "bento/ubuntu-24.04": Ubuntu 24.04 base image published by the Bento project, compatible with VirtualBox.box_check_update = false: avoids checking for image updates on every boot.synced_folder ... disabled: true: disables the/vagrantshared folder, which we don't need and which sometimes causes problems.
- Each machine's definition (
config.vm.define name):hostname: the machine's name inside the operating system.private_network: a private network between your computer and the VMs with the given fixed IP. The192.168.56.0/24range is the one VirtualBox allows by default for host-only networks.provider "virtualbox"block: the name shown in VirtualBox (aurora-web1…), memory and CPUs.
- Provisioning (
provision "shell"): a small script that runs asrootthe first time the machine is created:install -d -m 700 ...: creates thevagrantuser's~/.sshwith the right permissions.grep -qxF ... || echo ... >>: adds the public key only if it wasn't already there. Notice: this is a small example of idempotency done "by hand" in bash. With Ansible you won't have to write these checks.chown/chmod 600: SSH requiresauthorized_keysto belong to the user and not be accessible by others.
We use minimal Vagrant provisioning only to get SSH access ready. Everything else (packages, users, services) will be done by Ansible.
- Starting and managing the machines
From the lab directory:
The first time, Vagrant downloads the bento/ubuntu-24.04 image (a few hundred MB) and then creates and boots the three machines. You will see something like:
Bringing machine 'web1' up with 'virtualbox' provider...
Bringing machine 'web2' up with 'virtualbox' provider...
Bringing machine 'db1' up with 'virtualbox' provider...
==> web1: Importing base box 'bento/ubuntu-24.04'...
...
==> web1: Running provisioner: shell...
...
==> db1: Machine booted and ready!Check their status:
Current machine states:
web1 running (virtualbox)
web2 running (virtualbox)
db1 running (virtualbox)Vagrant commands you will use often:
| Command | What it does | When to use it |
|---|---|---|
vagrant up |
Creates (if they don't exist) and boots the machines | When you start working |
vagrant up web1 |
Same, only for web1 |
To save resources |
vagrant status |
Shows each machine's state | To check what is running |
vagrant halt |
Shuts down the machines, keeping their disks | When you finish your study session |
vagrant ssh web1 |
Logs into web1 with Vagrant's internal key |
Quick debugging |
vagrant ssh-config web1 |
Shows the SSH connection details Vagrant uses | To understand or reuse its configuration |
vagrant snapshot save web1 clean |
Saves a snapshot of the current state | Before risky experiments |
vagrant destroy -f |
Deletes the machines completely | To start from scratch |
Tip: once your three machines are freshly created and reachable, save a "clean" snapshot of each one (
vagrant snapshot save clean, without a machine name, saves it for all of them). That way you can go back to the starting point withvagrant snapshot restore cleanand check that your automation works from scratch.
Alternative: using Vagrant's key
Vagrant also generates its own private key for each machine in lab/.vagrant/machines/<name>/virtualbox/private_key. You could connect with it:
ssh -i .vagrant/machines/web1/virtualbox/private_key [email protected]It works, but it has drawbacks: there's a different key per machine, the path is long, and it changes if you destroy and recreate the machines. That's why in this course we will use our own aurora_ed25519 key, which is how you would work with real servers.
- Checking SSH access manually
Before Ansible comes into play, verify that you can connect to each machine over SSH. If SSH doesn't work by hand, Ansible won't work either.
ssh -i ~/.ssh/aurora_ed25519 [email protected]The first time, SSH shows you the server's fingerprint and asks whether you trust it:
The authenticity of host '192.168.56.11 (192.168.56.11)' can't be established.
ED25519 key fingerprint is SHA256:3kF1v0n8...(fictitious fingerprint)...
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.56.11' (ED25519) to the list of known hosts.
vagrant@web1:~$- Type
yes: the fingerprint is saved in~/.ssh/known_hostsand you won't be asked again. - The
vagrant@web1:~$prompt confirms you are insideweb1. Leave withexit.
Now check, without logging in interactively, the two requirements Ansible will need: Python 3 and passwordless sudo:
for ip in 192.168.56.11 192.168.56.12 192.168.56.21; do
ssh -i ~/.ssh/aurora_ed25519 vagrant@$ip 'hostname; python3 --version; sudo -n true && echo "sudo OK"'
doneExplanation:
- The
forloop iterates over the three IPs. - Inside the single quotes is the command that runs on the remote server:
hostname: prints the machine's name.python3 --version: confirms Python is installed.sudo -n true && echo "sudo OK":-n(non-interactive) makessudofail instead of prompting for a password. If it printssudo OK, thevagrantuser can escalate privileges without a password.
Expected output (after accepting the web2 and db1 fingerprints the first time):
If all three machines respond like this, your lab is ready for Ansible.
~/.ssh/config (optional, but recommended)
~/.ssh/config (optional, but recommended)Typing -i ~/.ssh/aurora_ed25519 [email protected] every time gets tedious. The ~/.ssh/config file lets you define aliases with their connection options. Add this to the end of ~/.ssh/config (create it if it doesn't exist):
# --- Aurora Store lab ---
Host web1
HostName 192.168.56.11
Host web2
HostName 192.168.56.12
Host db1
HostName 192.168.56.21
Host web1 web2 db1 192.168.56.*
User vagrant
IdentityFile ~/.ssh/aurora_ed25519
IdentitiesOnly yes- Each
Host web1block maps theweb1alias to its IP (HostName). - The last block applies common options to the three aliases and to any IP in the lab range:
User vagrant: default remote user.IdentityFile: private key to use.IdentitiesOnly yes: uses only that key, preventing SSH from trying every key in your agent (which can cause "too many authentication failures" errors).
Lock down the file's permissions and try it:
Ansible uses the system's OpenSSH client, so it also honors this file. Even so, in this course we will explicitly set the user and key in Ansible's configuration, so that the project works the same on any computer.
- Saving your work in git
Record what you have created in git:
cd ~/aurora-infra
git status
git add .gitignore lab/Vagrantfile
git commit -m "Aurora Store lab: Vagrantfile with web1, web2 and db1"git status: shows which files are new. Check thatlab/.vagrant/does not appear (.gitignoreexcludes it).git add: stages the files for the commit.git commit -m: saves a snapshot with a descriptive message.
Current repository layout:
The private key
~/.ssh/aurora_ed25519lives outside the repository, in your~/.ssh. Never store private keys in git.
- Alternatives: Docker containers and cloud machines
If you can't use VirtualBox (Apple Silicon, a low-memory computer, corporate restrictions), you have other options. What matters is keeping the same names, groups and SSH access, so the rest of the course works the same way.
10.1 Docker containers with SSH
You can simulate the servers with Ubuntu containers running an SSH server. Here is a minimal Dockerfile (save it, for example, as aurora-infra/lab/docker/Dockerfile):
FROM ubuntu:24.04
RUN apt-get update && \
apt-get install -y --no-install-recommends openssh-server python3 sudo && \
useradd -m -s /bin/bash vagrant && \
echo "vagrant ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/vagrant && \
mkdir -p /run/sshd /home/vagrant/.ssh && \
rm -rf /var/lib/apt/lists/*
COPY aurora_ed25519.pub /home/vagrant/.ssh/authorized_keys
RUN chown -R vagrant:vagrant /home/vagrant/.ssh && chmod 700 /home/vagrant/.ssh && chmod 600 /home/vagrant/.ssh/authorized_keys
CMD ["/usr/sbin/sshd", "-D"]- Installs
openssh-server,python3andsudo, and creates thevagrantuser with passwordlesssudo, mimicking the VMs. - Copies your public key (copy it next to the
Dockerfilefirst) asauthorized_keys. sshd -Dkeeps the SSH server in the foreground as the container's main process.
You would then create a network with the lab subnet and the three containers with their IPs:
cd ~/aurora-infra/lab/docker
cp ~/.ssh/aurora_ed25519.pub .
docker build -t aurora-node .
docker network create --subnet 192.168.56.0/24 aurora-net
docker run -d --name web1 --hostname web1 --network aurora-net --ip 192.168.56.11 aurora-node
docker run -d --name web2 --hostname web2 --network aurora-net --ip 192.168.56.12 aurora-node
docker run -d --name db1 --hostname db1 --network aurora-net --ip 192.168.56.21 aurora-nodeAn important limitation: containers normally don't run systemd, so managing services (starting nginx or PostgreSQL as a service) behaves differently than on a VM. It's fine for the first modules, but VMs are preferable for following the whole course. (On Docker Desktop for macOS/Windows, the container network IPs aren't always reachable from the host; in that case, publish each container's port 22 with -p 2211:22, and so on.)
10.2 Cloud virtual machines
Another option is to create three small Ubuntu 24.04 VMs on your favorite cloud provider:
- Name them
web1,web2anddb1. - Use the
aurora_ed25519.pubpublic key when creating them. - The remote user will be whatever the image dictates (usually
ubuntu); write it down, because you will have to specify it in the inventory. - Throughout the course, replace the
192.168.56.xIPs with the public or private IPs the provider assigns you, and open port 22 only to your IP. - Shut them down or delete them when you're not using them to avoid costs.
| Option | Advantages | Drawbacks |
|---|---|---|
| Vagrant + VirtualBox (recommended) | Free, local, fixed IPs, real systemd, snapshots | Needs RAM; problems on Apple Silicon |
| Docker containers | Very lightweight and quick to create | No systemd by default; different networking on Docker Desktop |
| Cloud VMs | Realistic environment; uses no local resources | Cost; IPs and user change; exposure to the Internet |
Common Mistakes and Tips
vagrant upfails with a host-only network error: by default VirtualBox 7 only allows the192.168.56.0/21range. Use exactly the course's IPs or adjust/etc/vbox/networks.conf.- "~/.ssh/aurora_ed25519.pub not found": you generated the key with a different name or after
vagrant up. Generate it and runvagrant provisionto apply the provisioning script again. Permission denied (publickey): the key isn't inauthorized_keys, you're using a different key, or the private key's permissions aren't600. Diagnose withssh -v web1.WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!: you destroyed and recreated a machine with the same IP and its fingerprint changed. In the lab this is expected: remove the old fingerprint withssh-keygen -R 192.168.56.11(andssh-keygen -R web1if you use the alias) and connect again. In production, however, investigate before doing so.- Slow computer: start only what you need (
vagrant up web1 db1) and shut down withvagrant haltwhen you're done. - Tip: don't make manual changes inside the VMs "just to try something". If you do, restore the
cleansnapshot; that way your lab will never suffer from configuration drift.
Exercises
Exercise 1: Lab up and running
Build the complete lab and show that it works by displaying the output of vagrant status and of the check loop from section 7.
Exercise 2: Adding a machine
Aurora Store's management wants to try out a third web server. Modify the Vagrantfile to add web3 with IP 192.168.56.13, 1 GB of RAM and 1 CPU; boot it, check SSH access with the web3 alias, and then remove it, leaving the lab as it was.
Exercise 3: Recovering after recreating a machine
Destroy and recreate web2 (vagrant destroy -f web2 && vagrant up web2). Try connecting with ssh web2. What happens and how do you fix it?
Solutions
Exercise 1.
cd ~/aurora-infra/lab
vagrant up
vagrant status
for h in web1 web2 db1; do ssh $h 'hostname; python3 --version; sudo -n true && echo "sudo OK"'; doneAll three machines should show up as running and, for each one, you should see its name, Python 3.12.x and sudo OK.
Exercise 2. Add a line to the MACHINES dictionary:
And an alias in ~/.ssh/config. Careful: SSH matches Host patterns against the name you type on the command line (web3), not against the IP, so you must also add web3 to the common options line (Host web1 web2 db1 web3 192.168.56.*):
Finally, remove the web3 line from the Vagrantfile and from ~/.ssh/config, and delete its fingerprint with ssh-keygen -R web3 && ssh-keygen -R 192.168.56.13. Use git diff to check that the Vagrantfile is back to how it was in the last commit.
Exercise 3. SSH shows WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! and refuses the connection: the new VM has generated different host keys and SSH suspects a possible attack. Since you know the cause is the recreation, delete the old fingerprints and connect again:
ssh-keygen -R web2
ssh-keygen -R 192.168.56.12
ssh web2 hostname # accept the new fingerprint with "yes"This same problem will affect Ansible if you recreate machines, so it's worth learning to recognize it.
Conclusion
You have a reproducible lab that mimics Aurora Store's infrastructure: web1 and web2 as future web servers and db1 as the future database server, all running Ubuntu 24.04 with Python 3 and key-based SSH access for the vagrant user. You have also created the aurora-infra/ repository under git, with the lab in lab/ and a .gitignore that protects sensitive files. Before running your first Ansible command, it's worth understanding what happens under the hood when you do: in the next lesson, Ansible Architecture, you will see how the control node and the managed nodes communicate, how a module is executed and what idempotency really means.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
