EN

Applications

Automate Your Servers with Ansible

Get started with Ansible: installation, inventory, playbook, roles and secret encryption with Ansible Vault for your Debian and Ubuntu servers.

7 min read, updated on 18 November 2026

On this page

Your values

Enter them once and the commands in this guide update.

Ansible lets you describe your servers' configuration in YAML files, then apply it over SSH. No agent needs to be installed on the managed servers: they only need SSH and Python.

In this guide, you will create a small project that installs Nginx, publishes a demo page and deploys a secret encrypted with Ansible Vault.

Term Meaning
Control node Machine where Ansible is installed and from which you run commands
Managed node Server administered by Ansible
Inventory List of servers and their groups
Task A single action, handled by a module
Playbook YAML file that maps tasks to servers
Role Reusable set of tasks, templates and variables
Vault Mechanism for encrypting sensitive data

Prerequisites

  • A control node running Linux: your computer or an administration server
  • One or more managed servers running Debian 12/13 or Ubuntu 22.04/24.04
  • An SSH user on each managed server, in the sudo group
  • SSH key authentication
  • The SSH port reachable from the control node, and port 80 for the demo page

Choose the control node

The Ansible version available depends on the Python version on the control node:

Control node system Python Version installed by pipx Status
Debian 13 3.13 Ansible 15 (ansible-core 2.22) Recommended
Ubuntu 24.04 3.12 Ansible 14 (ansible-core 2.21) Recommended
Debian 12 3.11 Ansible 12 (ansible-core 2.19) End of life in November 2026
Ubuntu 22.04 3.10 Ansible 10 (ansible-core 2.17) End of life

This constraint applies to the control node. Debian 12 and Ubuntu 22.04 remain usable as managed servers.

Install Ansible

On the control node, install Ansible with pipx, a method described in the official documentation:

Terminal
sudo apt update
sudo apt install -y pipx
pipx ensurepath

Close and reopen your session to pick up the PATH, then install the full package:

Terminal
pipx install --include-deps ansible
ansible --version

Prepare SSH access

Create a key if you do not have one, then copy it to the managed server:

Terminal
ssh-keygen -t ed25519 -C "ansible"
ssh-copy-id YOUR_USER@YOUR_SERVER_IP
ssh -t YOUR_USER@YOUR_SERVER_IP 'python3 --version && sudo -v'

The first connection asks you to confirm the server's fingerprint: check it, because Ansible will later refuse an unknown host. To harden SSH access, see the Secure your server guide.

Create the project

Terminal
mkdir -p ~/infra/group_vars/web
cd ~/infra
nano ansible.cfg
Configuration
[defaults]
inventory = inventory.ini
roles_path = roles

Write the inventory

Terminal
nano inventory.ini
Configuration
[web]
web1 ansible_host=YOUR_SERVER_IP ansible_user=YOUR_USER

If your SSH port is not 22, add ansible_port=YOUR_PORT to the server's line. Then check the inventory and the connection:

Terminal
ansible-inventory --graph
ansible all -m ansible.builtin.ping
ansible web -m ansible.builtin.command -a "uptime"

The ping module must answer pong. It checks the SSH connection and Python: it is not a network ping.

Write a first playbook

Terminal
nano premier-playbook.yml
YAML
---
- name: Prepare the web servers
  hosts: web
  become: true
  tasks:
    - name: Install Nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Enable and start Nginx
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

become: true runs the tasks with sudo. First test without changing anything, then apply:

Terminal
ansible-playbook premier-playbook.yml --check --diff
ansible-playbook premier-playbook.yml

Add --ask-become-pass if sudo asks for a password. Then run the playbook again: the recap must show changed=0, because the desired state has already been reached. This is the principle of idempotence.

Organize the code with a role

Generate the structure of a role named web:

Terminal
ansible-galaxy role init --init-path roles web

Default variables

File roles/web/defaults/main.yml:

YAML
---
web_domain: your-domain.com
web_root: /var/www/demo
app_config_dir: /etc/demo-app

Tasks

File roles/web/tasks/main.yml:

YAML
---
- name: Install Nginx
  ansible.builtin.apt:
    name: nginx
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Create the site folder
  ansible.builtin.file:
    path: "{{ web_root }}"
    state: directory
    owner: root
    group: root
    mode: "0755"

- name: Publish the demo page
  ansible.builtin.copy:
    dest: "{{ web_root }}/index.html"
    content: "<h1>Server managed by Ansible: {{ inventory_hostname }}</h1>\n"
    owner: root
    group: root
    mode: "0644"

- name: Deploy the site configuration
  ansible.builtin.template:
    src: site.conf.j2
    dest: /etc/nginx/sites-available/demo.conf
    owner: root
    group: root
    mode: "0644"
  notify: Reload Nginx

- name: Enable the site
  ansible.builtin.file:
    src: /etc/nginx/sites-available/demo.conf
    dest: /etc/nginx/sites-enabled/demo.conf
    state: link
  notify: Reload Nginx

- name: Create the application configuration folder
  ansible.builtin.file:
    path: "{{ app_config_dir }}"
    state: directory
    owner: root
    group: root
    mode: "0750"

- name: Deploy the application secret
  ansible.builtin.copy:
    dest: "{{ app_config_dir }}/app.env"
    content: "APP_TOKEN={{ app_token }}\n"
    owner: root
    group: root
    mode: "0600"
  no_log: true

- name: Enable and start Nginx
  ansible.builtin.service:
    name: nginx
    state: started
    enabled: true

no_log: true keeps the secret from appearing in Ansible's output.

Handler

File roles/web/handlers/main.yml. A handler runs only if a task has notified it, and only once, at the end of the task series:

YAML
---
- name: Reload Nginx
  ansible.builtin.service:
    name: nginx
    state: reloaded

Jinja2 template

File roles/web/templates/site.conf.j2:

Nginx
server {
    listen 80;
    listen [::]:80;
    server_name {{ web_domain }};
    root {{ web_root }};
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Main playbook

File site.yml, at the root of the project:

YAML
---
- name: Configure the web servers
  hosts: web
  become: true
  roles:
    - web

Protect secrets with Ansible Vault

Separate ordinary variables from encrypted ones. The group_vars/web/vars.yml file stays readable and references the secret:

YAML
---
app_token: "{{ vault_app_token }}"

Create the encrypted file. Choose a strong password when the command asks for one:

Terminal
EDITOR=nano ansible-vault create group_vars/web/vault.yml

Write the secret in it:

YAML
---
vault_app_token: "REPLACE_WITH_YOUR_SECRET"

Once saved, the file starts with $ANSIBLE_VAULT and its content is unreadable. The useful commands are:

Command Effect
ansible-vault view group_vars/web/vault.yml Display the content
ansible-vault edit group_vars/web/vault.yml Edit the content
ansible-vault rekey group_vars/web/vault.yml Change the password

Run the deployment

Allow web traffic on the managed server if UFW is active, then run a dry run and the deployment:

Terminal
ssh -t YOUR_USER@YOUR_SERVER_IP 'sudo ufw allow 80/tcp'
ansible-playbook site.yml --syntax-check --ask-vault-pass
ansible-playbook site.yml --check --diff --ask-vault-pass
ansible-playbook site.yml --ask-vault-pass

To automate, keep the password in a file outside the project:

Terminal
install -m 600 /dev/null ~/.ansible-vault-infra
nano ~/.ansible-vault-infra
ansible-playbook site.yml --vault-password-file ~/.ansible-vault-infra

Check the result

Terminal
curl -H 'Host: your-domain.com' http://YOUR_SERVER_IP/
ansible web -b -m ansible.builtin.stat -a "path=/etc/demo-app/app.env"
ansible-playbook site.yml --ask-vault-pass

The page must display the name web1, the app.env file must have mode 0600, and the last run must end with changed=0.

This demo page is served over HTTP. For a real site, add a certificate by following the Install an SSL Certificate with Let's Encrypt guide.

Version and back up the project

Ansible does not keep any state: your project is the source of truth. Put it in a private Git repository and exclude local files:

Terminal
cd ~/infra
git init
printf '%s\n' '*.retry' '.vault-pass*' > .gitignore
git add .
git status
git commit -m "Initial Ansible project"

Before the first commit, check that group_vars/web/vault.yml is indeed encrypted:

Terminal
head -n 1 group_vars/web/vault.yml

Save the Vault password in a password manager, separately from the repository: without it, the secrets cannot be recovered.

Update Ansible

Terminal
pipx upgrade --include-injected ansible
ansible --version

If you use the PPA, run sudo apt update then sudo apt install --only-upgrade ansible. After a major update, read the porting guide and run your playbooks again with --check --diff.

Troubleshooting

ansible: command not found

The pipx folder is not in the PATH. Run pipx ensurepath, then open a new session.

UNREACHABLE and Permission denied (publickey,password)

Test the connection with the same parameters, then run Ansible again in verbose mode:

Terminal
ssh -p 22 YOUR_USER@YOUR_SERVER_IP
ansible all -m ansible.builtin.ping -vvv

Check ansible_host, ansible_user, ansible_port and the key used.

Host key verification failed

The server's fingerprint is unknown or has changed. After a legitimate reinstallation, remove the old entry, then reconnect and check the new fingerprint:

Terminal
ssh-keygen -R YOUR_SERVER_IP
ssh YOUR_USER@YOUR_SERVER_IP

Missing sudo password

Add --ask-become-pass, or configure sudo according to your security policy.

Attempting to decrypt but no vault secrets found

The playbook is reading an encrypted file without a password. Add --ask-vault-pass or --vault-password-file.

Decryption failed

The password does not match the one used for the file. Also check that the password file does not contain a different value.

Could not get lock /var/lib/dpkg/lock-frontend

Another APT operation is in progress, often automatic updates. Wait for it to finish, or add lock_timeout: 300 to the ansible.builtin.apt task.

Ansible ignores ansible.cfg

Ansible ignores this file if the current folder is world-writable. Fix the permissions with chmod o-w ~/infra, then check the result with ansible --version, which shows the loaded file.

Going further

To create infrastructure or generate files before configuring it, see the Getting Started with Terraform guide. To centralize your secrets, see Install HashiCorp Vault.

References