How to Provision Bare Metal Servers with Ansible
Bare metal is the go to choice for developers looking for control over the hardware. Dedicated cores with no neighbors competing for them, direct access to the disks, and a kernel you choose. Managed platforms offer the opposite trade: someone else handles the setup, patching, and configuration, and in exchange you run what their runtime supports on hardware you never see. Bare metal hands the control back, but also the work along with it.
Every server needs the same packages, the same admin account, the same Secure Shell (SSH) settings, and the same firewall rules. One node left with PasswordAuthentication yes stays open to password guessing while the rest of the fleet is locked down. Ad hoc shell scripts remove the repetition but not the drift, since a script that does not check the current state can behave unpredictably on a server someone has already changed.
Ansible closes that gap without sacrificing control. It covers both halves of the job: provisioning the servers from your provider and configuring what comes up. You describe the state you want in YAML Ain't Markup Language (YAML) files, and Ansible applies it over SSH with nothing installed on the server.
Many of its modules are idempotent: they compare the current state against the requested state and act only when something differs, so rerunning a playbook leaves a correct server untouched and pulls a drifted one back into line.
The cost is a short setup on your own machine. In this guide, you install Ansible, then use one playbook to provision two servers via the Cherry Servers API and a second to configure them, leaving each patched, firewalled, and reachable only via a named admin account using SSH keys.
Run your deployments in a scalable and cost-effective open cloud infrastructure. Cherry Servers' secure virtual private servers offer automatic scaling, flexible pricing, and 24/7 technical support. Our pre-defined Ansible module helps you automate the installation and configuration.
#Prerequisites
Ansible does not install the operating system itself. The provider's Application programming interface (API) deploys the image, so Ansible calls that API to order the servers and then configures what comes up. Steps 4. through 11. use the Cherry Servers API and automation tooling to create the hardware, while the baseline playbook in Steps 13. through 23. applies to any Linux server Ansible can reach.
Every command output in this guide comes from a real run of the sequence.
Before you start, make sure you have:
-
A control node, the machine Ansible runs from, with Linux and Python 3.12 or later, which current ansible-core requires. Ubuntu 24.04 or later works directly, and on Windows, Windows Subsystem for Linux 2 (WSL2) with Ubuntu gives you the same environment.
-
A Cherry Servers account with a project and enough credit for a short test, since the playbook orders hardware through the API.
-
Network access from the control node to each server over SSH, which is how Ansible reaches them. This guide uses each server's primary public IPv4 address, though a reachable private address works too.
-
Familiarity with a Linux terminal and a text editor.
During testing, the control node ran Ubuntu 26.04 under WSL2 with Python 3.14, which is why the sample output shows that version rather than 3.12, which an Ubuntu 24.04 control node would report.
The run used Ansible 14.5.0, ansible-core 2.21.5, the cherryservers.cloud collection 3.0.0, and the ubuntu_24_04_64bit image, which deployed Ubuntu 24.04.5 LTS on the servers.
Rent Dedicated Servers
Deploy custom or pre-built dedicated bare metal. Get full root access, AMD EPYC and Ryzen CPUs, and 24/7 technical support from humans, not bots.
#Instructions to Provision Bare Metal Through Ansible
#Prepare the Control Node
Steps 1. to 12. take place on the control node.
#Step 1: Install Ansible
Ubuntu 24.04's default repositories carry ansible-core 2.16, older than the Cherry Servers collection requires. pipx, a tool that installs Python applications in isolated environments, installs the current release and keeps Ansible and its dependencies off the system Python.
-
On the control node, install pipx by running the command:
sudo apt update sudo apt install -y pipx -
Add the pipx application directory to your
PATHwith:pipx ensurepath -
Close the terminal and open a new one so the
PATHchange takes effect. -
Install Ansible with its command-line tools:
pipx install --include-deps ansibleThe
--include-depsflag addsansible-playbook,ansible-galaxy, and the other tools alongside theansiblecommand. The fullansiblepackage also bundles collections, which are packaged sets of modules. This guide usescommunity.generalandansible.posixfrom that bundle. -
Confirm the installed version using:
ansible --versionThe output should begin with:
Output
ansible [core 2.21.5] config file = None configured module search path = ['/home/ubuntu/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/ubuntu/.local/share/pipx/venvs/ansible/lib/python3.14/site-packages/ansible ansible collection location = /home/ubuntu/.ansible/collections:/usr/share/ansible/collections executable location = /home/ubuntu/.local/bin/ansible python version = 3.14.4 (main, Aug 20 2026, 10:41:58) [GCC 15.2.0] (/home/ubuntu/.local/share/pipx/venvs/ansible/bin/python) jinja version = 3.1.6 pyyaml version = 6.0.3 (with libyaml v0.2.5)Please note that ansible-core must be 2.18 or later for the Cherry Servers collection.
#Step 2: Install the Cherry Servers Collection
The cherryservers.cloud collection adds modules for servers, SSH keys, floating IPs, and storage, plus an inventory plugin that reads your servers from the API.
This guide uses two of those modules and the plugin. The other can be found in the collection repository. This process requires ansible-core 2.18 or later and Python 3.11 or later.
-
Install the collection using:
ansible-galaxy collection install cherryservers.cloud -
Confirm the installed version with:
ansible-galaxy collection list cherryservers.cloudYou should get a return like this:
Output
# /home/ubuntu/.ansible/collections/ansible_collections Collection Version ------------------- ------- cherryservers.cloud 3.0.0
#Step 3: Generate an SSH Key Pair
The creation playbook uploads your public key to Cherry Servers so each new server accepts root logins from the control node at first boot. The key must exist before you order anything.
-
Create the project directory and move into it using the command:
mkdir ~/bare-metal-ansible && cd ~/bare-metal-ansibleKeep this directory inside the Linux filesystem. Ansible ignores a configuration file in a world-writable directory, which on WSL includes anything under
/mnt/c. -
Generate an Ed25519 key pair with:
ssh-keygen -t ed25519 -C "ansible-control-node" -
Press Enter to accept the default path,
~/.ssh/id_ed25519. Press Enter twice more to skip the passphrase, which keeps playbook runs non-interactive.This command creates a private key at
~/.ssh/id_ed25519and a public key at~/.ssh/id_ed25519.pub. Only the public key leaves the control node. If you set a passphrase, load it into the SSH agent withssh-add ~/.ssh/id_ed25519before running a playbook.
#Create the Servers
The creation playbook needs four values from your account: an API token, a project ID, a plan slug, and a region slug.
#Step 4: Create the API Token
-
In a browser, sign in to the Cherry Servers client portal at
portal.cherryservers.com. -
Open the user menu and select "API Keys". The page sits at
portal.cherryservers.com/settings/api-keys. -
Create a new key and copy the token.
-
On the control node, export the token:
export CHERRY_AUTH_TOKEN="your-api-token"The collection reads the token from
CHERRY_AUTH_TOKEN, which keeps it out of your playbook files. The variable lasts only for the current terminal session, so export it again after reopening the terminal.
#Step 5: Find Your Team and Project IDs
The creation playbook and the inventory file both need your project ID. Projects belong to a team, so the team ID comes first.
-
List your teams:
curl -s -H "Authorization: Bearer $CHERRY_AUTH_TOKEN" \ https://api.cherryservers.com/v1/teams | python3 -m json.toolNote the
idvalue near the top of the output, this will be used in the upcoming step. The Cherry Servers API reference documents these endpoints and the rest of the API. -
List the projects for that team, replacing “TEAM_ID” with your team ID:
curl -s -H "Authorization: Bearer $CHERRY_AUTH_TOKEN" \ https://api.cherryservers.com/v1/teams/TEAM_ID/projects | python3 -m json.toolNote down the project
idfor the next step.
#Step 6: Find a Plan with Stock
A plan is orderable only where it has stock, and the API lists plans of several types. Bare metal plans carry "type": "baremetal", while others are shared or dedicated virtual machines.
- First of all, list the bare metal plans that have stock, sorted by price by running, replacing “TEAM_ID” with your team ID:
curl -s -H "Authorization: Bearer $CHERRY_AUTH_TOKEN" \
https://api.cherryservers.com/v1/teams/TEAM_ID/plans \
| python3 -c "
import json,sys
unit='Hourly'
rows=[]
for p in json.load(sys.stdin):
if p.get('type')!='baremetal': continue
price=next((x for x in p.get('pricing',[]) if x['unit']==unit),None)
if price is None: continue
imgs=[s['image']['slug'] for s in p.get('softwares',[])]
for r in p.get('available_regions') or []:
if r.get('stock_qty',0)>0:
rows.append((price['price'],price['currency'],p['slug'],r['slug'],r['stock_qty'],'ubuntu_24_04_64bit' in imgs))
for c,cur,plan,region,stock,u24 in sorted(rows):
print(f'{c:<9} {cur:<5} {plan:<28} {region:<14} stock={stock:<4} ubuntu24={u24}')
"
The API prices each plan several ways. You can set it to unit Hourly, Monthly, Quarterly, Semiannually, or Annually to see the rate you plan to pay, and set cycle in Step 7 to match.
This guide is based on the hourly billing option. Our test priced e5-1620v4 at $0.2305 hourly against $134.55 monthly, so the two met at roughly 584 hours, or 24 days of continuous running. Below that, the hourly cycle costs less, which is the trade-off between hourly and fixed-term billing.
Each line shows a price and its currency for the unit you chose, a plan slug, a region slug, the stock count, and whether that plan offers the Ubuntu 24.04 image. Stock is counted per region, so a plan showing fewer units than the servers you want cannot fill the order. This guide used e5-1620v4 in LT-Siauliai.
The first lines of the output read:
Output0.0983 USD e3-1240v3 LT-Siauliai stock=9 ubuntu24=True
0.1182 USD e3-1240v5 LT-Siauliai stock=7 ubuntu24=True
0.2305 USD e3-1240lv5 LT-Siauliai stock=31 ubuntu24=True
0.2305 USD e5-1620v4 LT-Siauliai stock=108 ubuntu24=True
0.3588 USD e5-1650v3 LT-Siauliai stock=9 ubuntu24=True
Image slugs are not consistently formatted. Ubuntu 24.04 is ubuntu_24_04_64bit, while Ubuntu 22.04 is ubuntu_22_04, so it’s important to ensure the slug you use matches the API.
#Step 7: Write the Creation Playbook
The creation playbook will run against the API from the control node, so it targets localhost rather than a server. It uploads the SSH key, looks up the key's ID, and then orders each server.
-
In
~/bare-metal-ansible, open a new file with your editor. This guide uses nano:nano create_servers.yml -
Paste in the following, replacing
project_id,region, andplanwith the values you identified earlier. It should look something like this:--- - name: Create bare metal servers on Cherry Servers hosts: localhost connection: local gather_facts: false vars: project_id: 163449 region: LT-Siauliai plan: e5-1620v4 ssh_key_label: ansible-control-node server_names: - node01 - node02 tasks: - name: Upload the control node SSH public key cherryservers.cloud.sshkey: label: "{{ ssh_key_label }}" key: "{{ lookup('ansible.builtin.file', '~/.ssh/id_ed25519.pub') }}" state: present - name: Look up the SSH key ID cherryservers.cloud.sshkey_info: label: "{{ ssh_key_label }}" register: key_info - name: Create the servers and wait for them to become active cherryservers.cloud.server: project_id: "{{ project_id }}" region: "{{ region }}" plan: "{{ plan }}" image: ubuntu_24_04_64bit hostname: "{{ item }}" ssh_keys: - "{{ key_info.cherryservers_sshkeys[0].id }}" tags: role: bare_metal active_timeout: 3600 state: active loop: "{{ server_names }}"
Then press Ctrl+X, type y, and press Enter to save and exit.
The sshkey module returns key data only outside check mode, so the separate sshkey_info lookup supplies the key ID.
Do not run this playbook with --check before the key exists, since the lookup finds nothing and the server task fails. The ssh_keys option takes integers, and tags takes a dictionary, which the inventory plugin later uses to find these servers.
With state: active, the module waits until each server finishes deploying, up to active_timeout.
The module identifies existing servers by project and hostname, so rerunning the playbook does not order duplicates. During testing, a second run reported no changes in under 30 seconds.
The cycle option sets the billing cycle and defaults to hourly. Match it to the pricing unit you chose in Step 6.
#Step 8: Run the Creation Playbook
Billing starts as each server is ordered, and interrupting the run does not cancel an order already placed.
- Order the servers with the command below, timing the run:
time ansible-playbook create_servers.yml
The run opens with two warnings about an empty host list. This is as expected, because this playbook targets localhost and no inventory exists until Step 9.
The loop deploys one server at a time, so the total grows with the server count. Deployment time varies with the hardware assigned. During testing, a run creating two servers took between 19 and 47 minutes end to end.
The output ends with the recap and the elapsed time:
Output[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [Create bare metal servers on Cherry Servers] *********************************************************************************************************************
TASK [Upload the control node SSH public key] **************************************************************************************************************************
changed: [localhost]
TASK [Look up the SSH key ID] ******************************************************************************************************************************************
ok: [localhost]
TASK [Create the servers and wait for them to become active] ***********************************************************************************************************
changed: [localhost] => (item=node01)
changed: [localhost] => (item=node02)
PLAY RECAP *************************************************************************************************************************************************************
localhost : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
real 32m50.028s
user 1m44.180s
sys 0m26.484s
#Connect Ansible to the Servers
The servers exist now, running a stock image with root SSH access and nothing else set up. Bringing them to your baseline is the second stage, and it starts with Ansible knowing they exist and how to reach them.
#Step 9: Create the Inventory File
Ansible reads the list of servers it manages from an inventory. A static file would need IP addresses you do not know until the servers exist, so the collection's inventory plugin reads them from the API at run time.
-
In
~/bare-metal-ansible, createcherryservers.yml:plugin: cherryservers.cloud.cherryservers project_id: 163449 status: deployed tags: role: bare_metal strict: true compose: ansible_host: (cs_ip_addresses | selectattr('type', 'equalto', 'primary-ip') | selectattr('address_family', 'equalto', 4) | first).address groups: bare_metal: true -
Here, Set the
project_idto your own, as found in Step 7.The plugin only loads files whose names end in
cherryservers.ymlorcherryservers.yaml. Thestatusandtagsoptions filter which servers appear, and the plugin prefixes each server's API data withcs_.The
composeblock setsansible_hostto the primary public IPv4 address. Cherry Servers labels the public addressprimary-ipand the internal oneprivate-ip, and theaddress_familyfilter selects IPv4 where a region also returns IPv6. Thestrict: truesetting turns a failed expression into an error rather than a silently missing variable.
#Step 10: Create the Configuration File
Without a configuration file, every command that reaches the servers needs flags for the inventory, the login user, and the key.
-
In
~/bare-metal-ansible, createansible.cfg:[defaults] inventory = cherryservers.yml remote_user = root private_key_file = ~/.ssh/id_ed25519 interpreter_python = auto_silentAnsible reads
ansible.cfgfrom the current directory, so run every later command from~/bare-metal-ansible. Without theinventoryline, commands fail with a message about an unmatched host pattern rather than a missing configuration, which is easy to misread. -
Confirm that Ansible found the file with:
ansible-config dump --only-changed | head -5The first line should name your
ansible.cfgpath.
#Step 11: Check What the Plugin Returns
The baseline playbook depends on two things the plugin supplies: a reachable address in ansible_host, and a host name matching the server's hostname. Confirm both before running anything against the servers.
-
List the hosts using the following command:
ansible-inventory --graphBoth servers should appear under
bare_metal:@all: |--@ungrouped: |--@bare_metal: | |--node02 | |--node01 -
Show one host's variables:
ansible-inventory --host node01The output will show every field the plugin returned for that server:
Output
{ "ansible_host": "185.8.104.214", "cs_hostname": "node01", "cs_id": 1036118, "cs_image": "ubuntu_24_04_64bit", "cs_ip_addresses": [ { "CIDR": "185.8.104.128/25", "address": "185.8.104.214", "address_family": 4, "id": "58285583-c574-5536-68f1-6b9073fbf149", "type": "primary-ip" }, { "CIDR": "10.200.97.0/24", "address": "10.200.97.45", "address_family": 4, "id": "2db6ffcf-c662-80f7-5fea-d8149b3d5204", "type": "private-ip" } ], "cs_name": "E5-1620v4", "cs_plan": "e5-1620v4", "cs_project_id": 163449, "cs_region": "LT-Siauliai", "cs_spot_market": false, "cs_ssh_keys": [ 19952 ], "cs_status": "deployed", "cs_storage_id": null, "cs_tags": { "role": "bare_metal" } }Check that
ansible_hostholds the public IPv4 address and that the host name matches the server's Cherry Servers hostname. The baseline playbook sets each server's hostname frominventory_hostname, which only works when those names match. -
Print each host's address by running:
ansible bare_metal -m debug -a 'var=ansible_host'Each host reports the address Ansible will connect to, which should look similar to this:
Output
node02 | SUCCESS => { "ansible_host": "185.8.104.155" } node01 | SUCCESS => { "ansible_host": "185.8.104.214" }Running
ansible-inventory --listinstead returns the same data with every API string wrapped in an internal marker, so Jinja never evaluates template syntax arriving from the API. That makesdebugthe clearer way to read these values.
#Step 12: Add the Host Keys and Test the Connection
Ansible checks host keys by default and refuses to connect to a server missing from ~/.ssh/known_hosts. New servers are missing from it by definition.
-
Add each server's host key, reading the addresses from the inventory:
ansible bare_metal -m debug -a 'var=ansible_host' \ | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' \ | xargs -I{} ssh-keyscan -H {} >> ~/.ssh/known_hosts -
Confirm Ansible reaches both servers with:
ansible bare_metal -m ansible.builtin.pingThe ping module is not an Internet Control Message Protocol (ICMP) ping. It logs in over SSH, runs a small Python program, and replies
pong, which proves SSH access, key authentication, and Python all work.Each server should return
SUCCESS, and the reply will name the Python interpreter it found. If everything is right so far, it will look something like this:Output
node01 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3.12" }, "changed": false, "ping": "pong" } node02 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3.12" }, "changed": false, "ping": "pong" }If a host reports
UNREACHABLEwithHost key verification failed, its key is missing fromknown_hosts. If the server was recently deployed, wait a minute for the first boot to finish and run the keyscan again.
#Configure the Servers
The second playbook brings every server to the same state. It updates the system first, creates an admin account second, and locks down SSH and the firewall last, so access never breaks halfway through a run.
#Step 13: Define the Shared Variables
Settings such as the admin username and the package list belong outside the playbook, so changing them does not mean editing tasks.
Ansible loads group_vars/bare_metal.yml automatically for every host in the bare_metal group.
-
Create the directory with this command:
mkdir -p group_vars -
Create the variables file using:
nano group_vars/bare_metal.yml -
Add the following information, then save and exit:
admin_user: deploy admin_ssh_key: "{{ lookup('ansible.builtin.file', '~/.ssh/id_ed25519.pub') }}" server_timezone: Etc/UTC base_packages: - curl - git - htop - vim - ufw - unattended-upgradesThe
admin_uservariable names the account that replaces root logins, andadmin_ssh_keyreads your public key from the control node. This guide usedEtc/UTCand the package list above.
Set both to suit your environment. Listing unattended-upgrades guarantees the package is present.
You can check systemctl status unattended-upgrades to see whether your image also enables it.
#Step 14: Start the Playbook
A playbook lists tasks Ansible runs against a group of hosts, in order, and each task calls a module, a unit of code performing one job.
Ansible ships each module to the server, runs it, and removes it, which is how Ansible works without an agent installed there.
-
In
~/bare-metal-ansible, create the playbook using this:nano provision.yml -
Add the play header:
--- - name: Provision bare metal servers hosts: bare_metal become: true tasks:
The become: true line runs each task with root privileges. It changes nothing on the first run, when Ansible logs in as root, and becomes essential once the playbook disables root login.
Leave this file open for now. In steps 15 through 20, we’ll add a block to the end of it, keeping the indentation shown, and in Step 20 we will check that the finished file parses.
#Step 15: Update System Packages
Deployed images lag behind current security patches.
- Add the package tasks:
- name: Upgrade all system packages
ansible.builtin.apt:
update_cache: true
cache_valid_time: 3600
upgrade: dist
tags: upgrade
- name: Install base packages
ansible.builtin.apt:
name: "{{ base_packages }}"
state: present
The cache_valid_time setting skips the cache refresh if one ran within the last hour. This playbook uses a handful of options across six modules, and the ansible.builtin reference documents the full set for each.
The upgrade tag lets a scheduled drift check skip this task with --skip-tags upgrade, since available patches would otherwise report a change whenever they exist. The upgrade: dist setting matches apt dist-upgrade and handles packages whose dependencies changed.
The base package task reports ok rather than changed when the image already carries those packages, which is the case on the Cherry Servers Ubuntu image.
#Step 16: Set the Hostname and Timezone
Matching hostnames and a shared timezone make logs from different servers line up during troubleshooting.
- Add these tasks:
- name: Set the hostname
ansible.builtin.hostname:
name: "{{ inventory_hostname }}"
- name: Set the timezone
community.general.timezone:
name: "{{ server_timezone }}"
The inventory_hostname variable holds each host's name from the inventory. During testing, both tasks reported ok, because the image already carried the Cherry Servers hostname and a UTC clock.
The tasks still belong in the playbook, since they hold that state on any image.
#Step 17: Create an Admin User
Sharing direct root access makes administrative changes harder to attribute to individual users, and a compromised root credential provides unrestricted access. A separate administrative account with controlled sudo access reduces the need for direct root logins.
-
Add the user and key tasks:
- name: Create the admin user ansible.builtin.user: name: "{{ admin_user }}" groups: sudo append: true shell: /bin/bash create_home: true - name: Add the SSH public key for the admin user ansible.posix.authorized_key: user: "{{ admin_user }}" key: "{{ admin_ssh_key }}" state: present ignore_errors: "{{ ansible_check_mode }}"The
ignore_errorsline applies only during a dry run. In check mode the admin user does not exist yet, and the key task fails withEither user must exist or you must provide full path to key file in check mode. The line lets the dry run finish, while a real run still stops on any error. -
Add the
sudotask:- name: Allow the admin user to run sudo without a password ansible.builtin.copy: dest: "/etc/sudoers.d/{{ admin_user }}" content: "{{ admin_user }} ALL=(ALL) NOPASSWD:ALL\n" owner: root group: root mode: "0440" validate: /usr/sbin/visudo -csf %sThe
validateline runsvisudoagainst the file before Ansible moves it into place, since a malformed sudoers file breakssudofor every user. The account has no password, soNOPASSWDis what makessudousable at all, and it lets later runs escalate privileges without a prompt.
#Step 18: Harden SSH
With the admin account in place, root and password logins are no longer needed. Ubuntu reads drop-in files from /etc/ssh/sshd_config.d/ before the main configuration file, and the SSH daemon, sshd, keeps the first value it finds for each setting. A file named 00-hardening.conf loads ahead of provider files such as 50-cloud-init.conf, which often enable password authentication.
- Add the hardening task:
- name: Ensure the SSH privilege separation directory exists
ansible.builtin.file:
path: /run/sshd
state: directory
owner: root
group: root
mode: "0755"
- name: Harden the SSH daemon
ansible.builtin.copy:
dest: /etc/ssh/sshd_config.d/00-hardening.conf
content: |
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
owner: root
group: root
mode: "0644"
validate: /usr/sbin/sshd -t -f %s
notify: Restart SSH
The sshd -t command checks the file for syntax errors before it goes live. It also needs /run/sshd, the privilege separation directory, which lives on tmpfs and can be absent after an openssh-server upgrade. During testing, one host hit that window and the task failed with Missing privilege separation directory: /run/sshd, which is why the task above it creates the directory first. Switching to sshd -T does not help, since it needs the same directory.
The notify line queues a handler, a task that runs once at the end of the play and only when a task notifying it reports a change. Step 20 defines that handler.
#Step 19: Configure the Firewall
Uncomplicated Firewall (UFW) is Ubuntu's front end for the kernel packet filter. The SSH rule comes first, because enabling a default deny policy before allowing SSH would cut off the control node.
- Add the firewall tasks after the hardening task, still inside the
tasksblock:
- name: Rate-limit incoming SSH connections
community.general.ufw:
rule: limit
port: ssh
proto: tcp
- name: Deny all other incoming traffic and enable UFW
community.general.ufw:
state: enabled
policy: deny
direction: incoming
The limit rule allows SSH but denies any address making six or more connection attempts within 30 seconds.
To open other services, such as ports 80 and 443 for a web server, add rules above the task that enables UFW.
#Step 20: Add the Handler
-
Add the handler at the end of
provision.yml, indented to the same level as thetaskskey:handlers: - name: Restart SSH ansible.builtin.service: name: ssh state: restartedRestarting the
sshservice leaves existing sessions open, including the one Ansible uses. -
Save and close the file. In nano, press Ctrl+X, type
y, and press Enter.The finished
provision.ymlshould read:Output
--- - name: Provision bare metal servers hosts: bare_metal become: true tasks: - name: Upgrade all system packages ansible.builtin.apt: update_cache: true cache_valid_time: 3600 upgrade: dist tags: upgrade - name: Install base packages ansible.builtin.apt: name: "{{ base_packages }}" state: present - name: Set the hostname ansible.builtin.hostname: name: "{{ inventory_hostname }}" - name: Set the timezone community.general.timezone: name: "{{ server_timezone }}" - name: Create the admin user ansible.builtin.user: name: "{{ admin_user }}" groups: sudo append: true shell: /bin/bash create_home: true - name: Add the SSH public key for the admin user ansible.posix.authorized_key: user: "{{ admin_user }}" key: "{{ admin_ssh_key }}" state: present ignore_errors: "{{ ansible_check_mode }}" - name: Allow the admin user to run sudo without a password ansible.builtin.copy: dest: "/etc/sudoers.d/{{ admin_user }}" content: "{{ admin_user }} ALL=(ALL) NOPASSWD:ALL\n" owner: root group: root mode: "0440" validate: /usr/sbin/visudo -csf %s - name: Ensure the SSH privilege separation directory exists ansible.builtin.file: path: /run/sshd state: directory owner: root group: root mode: "0755" - name: Harden the SSH daemon ansible.builtin.copy: dest: /etc/ssh/sshd_config.d/00-hardening.conf content: | PermitRootLogin no PasswordAuthentication no KbdInteractiveAuthentication no owner: root group: root mode: "0644" validate: /usr/sbin/sshd -t -f %s notify: Restart SSH - name: Rate-limit incoming SSH connections community.general.ufw: rule: limit port: ssh proto: tcp - name: Deny all other incoming traffic and enable UFW community.general.ufw: state: enabled policy: deny direction: incoming handlers: - name: Restart SSH ansible.builtin.service: name: ssh state: restarted -
Confirm the playbook parses by running:
ansible-playbook provision.yml --syntax-check
#Step 21: Preview the Changes
- Run in check mode with a diff by using:
ansible-playbook provision.yml --check --diff
Check mode reports what each task would change without changing anything. The --diff flag prints the lines each task would write:
OutputTASK [Harden the SSH daemon] ***************************************************
--- before
+++ after: /etc/ssh/sshd_config.d/00-hardening.conf
@@ -0,0 +1,3 @@
+PermitRootLogin no
+PasswordAuthentication no
+KbdInteractiveAuthentication no
changed: [node01]
The recap should show no failures, with one ignored task, which is the SSH key task described earlier:
node01 : ok=13 changed=7 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
node02 : ok=13 changed=7 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
#Step 22: Apply the Baseline
Before running this, open a second terminal and leave a root session to one server open with ssh root@SERVER_IP. This run disables root login, and that session is your way back in if key authentication for the admin account turns out to be broken. Close it once the second run succeeds.
-
Run the playbook with the following command:
time ansible-playbook provision.ymlThe run ends with the
Restart SSHhandler:Output
RUNNING HANDLER [Restart SSH] ************************************************** changed: [node01] changed: [node02] PLAY RECAP ********************************************************************* node01 : ok=13 changed=8 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 node02 : ok=13 changed=8 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 real 2m21.966sRoot login is now disabled, so Ansible needs to connect as the admin account from here on.
-
Open the configuration file with:
nano ansible.cfg -
Change the existing
remote_userline to the admin account, then save and exit:remote_user = deploy -
Run the playbook again using the same command as above:
ansible-playbook provision.ymlThe second run requires no further changes, which is the expected behavior of an idempotent playbook:
Output
PLAY RECAP ********************************************************************* node01 : ok=12 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 node02 : ok=12 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0The task count drops by one because the handler did not run, since no task notified it. This run also confirms the admin account and passwordless
sudowork, because every task escalated through thedeployuser.Rerunning the playbook later works as a drift check. Any managed setting that drifts from the state defined by the playbook can show up as
changedand return to that state. Ansible cannot detect changes to things the playbook does not manage.
#Step 23: Verify the Server State
The recap shows what Ansible did. These checks are intended to show what each server now enforces.
-
Check the active SSH settings by running:
ansible bare_metal -b -a "sshd -T" | grep -Ei "permitrootlogin|passwordauthentication|kbdinteractive"Each server should return:
Output
permitrootlogin no passwordauthentication no kbdinteractiveauthentication no -
Check the firewall using:
ansible bare_metal -b -a "ufw status verbose"Each server shows an active firewall with a default deny policy and rate-limit rules for both IPv4 and IPv6:
Output
node01 | CHANGED | rc=0 >> Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp LIMIT IN Anywhere 22/tcp (v6) LIMIT IN Anywhere (v6) node02 | CHANGED | rc=0 >> Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp LIMIT IN Anywhere 22/tcp (v6) LIMIT IN Anywhere (v6) -
Check the hostname and timezone:
ansible bare_metal -a "hostname" ansible bare_metal -a "timedatectl show -p Timezone --value"Each returns its value under a
CHANGEDheader:Output
node01 | CHANGED | rc=0 >> node01 node02 | CHANGED | rc=0 >> node02 node01 | CHANGED | rc=0 >> Etc/UTC node02 | CHANGED | rc=0 >> Etc/UTCThese ad hoc commands report
CHANGEDeven though they alter nothing. Thecommandmodule cannot tell whether a command made a change, which is why modules likeaptandcopycarry idempotence while raw commands do not. -
Check whether the upgrade left a restart pending:
ansible bare_metal -b -m shell -a "test -f /var/run/reboot-required && echo restart required || echo no restart needed"Each server answers
restart requiredorno restart needed. This uses theshellmodule rather than the defaultcommandmodule, becausecommandruns without a shell and would pass&&totestas an argument.A server that received a kernel upgrade will keep running the old kernel, so the patch will take effect only after a restart.
-
Set them to reboot when a short outage per server is acceptable:
ansible bare_metal -b -m ansible.builtin.reboot -a "reboot_timeout=1200"The module reboots the servers together and waits for each to come back, reporting how long it took. During testing, each returned in under 90 seconds. To restart a larger fleet one server at a time, put the task in a play with
serial: 1. -
Confirm the admin account accepts an interactive login, then type
exitto return to the control node:ssh deploy@SERVER_IP -
Next, confirm that the root does not accept interactive login:
ssh root@SERVER_IPIf the server rejects it as expected, you’ll see:
[email protected]: Permission denied (publickey).
#Clean Up
Servers will continue to be billed for as long as they exist, even if inactive, so be sure to terminate any you created for testing.
#Step 24: Remove the Test Servers
-
In
~/bare-metal-ansible, create the teardown playbook:nano delete_servers.yml -
Add the following, then save and exit:
--- - name: Delete the test bare metal servers hosts: localhost connection: local gather_facts: false vars: project_id: 163449 server_names: - node01 - node02 tasks: - name: Ensure the servers do not exist cherryservers.cloud.server: project_id: "{{ project_id }}" hostname: "{{ item }}" state: absent loop: "{{ server_names }}"Set
project_idto your own here too, and list the hostnames you created. -
Remove the host keys while the addresses are still in the inventory:
ansible bare_metal -m debug -a 'var=ansible_host' \ | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' \ | xargs -I{} ssh-keygen -R {}A later server may be assigned the same address, and a stale entry blocks the connection.
-
Preview, then delete. Deletion is permanent and destroys everything on the server:
ansible-playbook delete_servers.yml --check ansible-playbook delete_servers.yml -
Confirm the inventory is empty and the portal shows no servers in the project:
ansible-inventory --graphThe uploaded SSH key stays on your account and costs nothing. Remove it with the
sshkeymodule andstate: absentif you want a clean slate.
#What Causes Common Ansible Provisioning Errors?
Most failures in this workflow carry a recognizable message. The entries below follow the order in which they tend to appear.
#Couldn't Resolve Module or Action
An error such as couldn't resolve module/action 'cherryservers.cloud.server' means that the collection is not installed, which is the usual result of skipping Step 2, Install the Cherry Servers Collection.
The same error naming community.general.ufw or ansible.posix.authorized_key points at ansible-core being installed on its own rather than the full ansible package, which bundles both:
ansible-galaxy collection install cherryservers.cloud community.general ansible.posix
#auth_token Not Provided
Every Cherry Servers module reads the API token from CHERRY_AUTH_TOKEN, and that variable lasts only for the terminal session that set it. A task failing with auth_token not provided. usually means a new terminal, so export the token again.
Failed to validate auth token. means the variable holds something the API rejects, such as a placeholder being left unreplaced, or a revoked key.
#The Creation Task Fails While the Server Is Still Building
Two failures can look similar here. A server exceeding active_timeout fails the task, and so does a dropped connection while the module polls the API, which reports The read operation timed out. In both cases the order still stands, and the server keeps building.
Check its state through the API or the client portal, wait for deployed, then run the creation playbook again. This will recognize the existing server and continue. The playbook in Step 7 sets active_timeout to 3600 seconds, so if a deployment outruns that, you may need to raise it further.
#Could Not Match Supplied Host Pattern
This appears with warnings about an empty host list when Ansible did not read your ansible.cfg, or read it and found no matching group.
Confirm you are in the project directory, that ansible-config dump --only-changed names the expected file, and that the group name matches the one in your inventory. Ansible also ignores a configuration file in a world-writable directory, which on WSL includes anything under /mnt/c, so keep the project in the Linux filesystem.
#UNREACHABLE and Host Key Verification Failed
Ansible reports a host as UNREACHABLE when the SSH connection fails before any task runs. If the message includes Host key verification failed, the control node has no host key for that server, so you may need to repeat Step 12, “Add the Host Keys and Test the Connection”.
On a system without a graphical environment, this error usually arrives alongside ssh_askpass: exec(/usr/bin/ssh-askpass): No such file or directory, which reflects the missing prompt helper rather than a separate problem.
#Permission Denied (publickey)
After a successful baseline run, this usually means Ansible is still logging in as root. Set remote_user = deploy in ansible.cfg, or pass -u deploy.
On a newly created server, the server most likely does not have your key: check that the creation playbook passed the right key ID, that the private key is where private_key_file says, and that a passphrase-protected key is loaded in your SSH agent.
#Next Steps
The two playbooks cover the full path from an empty project to hardened servers, and both are safe to rerun.
Package the baseline as a reusable role, so other playbooks apply it by name, and split it into narrower roles such as ssh_hardening and firewall as it grows.
Lint the playbooks with ansible-lint, installed alongside Ansible through pipx inject ansible ansible-lint --include-apps, and test changes on one server with --limit node01 before rolling them out to the fleet. The Ansible command reference covers the flags you reach for less often.
To catch drift, run the baseline playbook with --check --diff on a schedule, from cron or CI. The scheduled job needs CHERRY_AUTH_TOKEN in its environment, since the inventory plugin reads the server list from the API.
The upgrade task reports a change whenever patches are available, so it carries the upgrade tag. Run scheduled checks with --skip-tags upgrade if you want drift reports to cover configuration only.
Once the baseline is in place, install a monitoring agent such as Prometheus Node Exporter, set up automated backups, or deploy a Kubernetes cluster across the nodes. Teams that already declare infrastructure in HashiCorp Configuration Language (HCL) can create the same hardware with Terraform and hand it to this baseline afterwards.
Get 100% dedicated resources for high-performance workloads.

