Swiss...
Ansible Automation: Managing a Fleet of Dedicated Servers at Scale
Stop SSHing into servers one by one. Build idempotent, version-controlled infrastructure automation that scales from 5 servers to 500 without changing your workflow.
November 19, 2026
by SwissLayer 22 min read
Ansible automation for managing dedicated server fleets on Swiss infrastructure

The Problem With Manual Server Management

When you have one or two servers, SSH and manual configuration work fine. You remember what you installed, where the config files are, and what changes you made. But infrastructure doesn't stay small. Add a third server. Then a fifth. Then you're managing fifteen Swiss dedicated servers across different roles — web servers, database replicas, monitoring nodes, backup targets — and suddenly you can't remember which servers have that critical security patch, which ones have the old SSH config, or why server-07 behaves differently from server-08.

This is the configuration drift problem. Every manual change creates divergence between servers that should be identical. Every emergency fix applied to one server but not others creates inconsistency. Every undocumented tweak becomes a landmine for future troubleshooting. The fleet becomes a collection of unique snowflakes instead of predictable, reproducible infrastructure.

Ansible solves this by turning server configuration into code. Instead of remembering commands and running them manually, you write playbooks that describe the desired state. Need to update SSH configs across 50 servers? Run one command. Need to deploy a new application version? One command. Need to audit which servers have a specific package installed? One command. The automation scales linearly — managing 50 servers takes the same effort as managing 5.

This guide covers Ansible from practical foundations to production patterns. We'll build inventory structures that organize complex fleets, write playbooks that handle real-world scenarios, structure code as reusable roles, manage secrets securely, and implement the patterns that make large-scale infrastructure manageable.

Installing Ansible

Ansible runs on a control node (your workstation or a management server) and connects to managed nodes via SSH. There's no agent to install on target servers — Ansible pushes commands over SSH and executes them remotely.

Control node installation (Ubuntu/Debian):

# Install from official PPA for latest version
apt update
apt install software-properties-common
add-apt-repository --yes --update ppa:ansible/ansible
apt install ansible

# Verify installation
ansible --version
# ansible [core 2.16.x]
#   config file = /etc/ansible/ansible.cfg
#   configured module search path = ['/root/.ansible/plugins/modules']
#   python version = 3.11.x

Control node installation (RHEL/Rocky/AlmaLinux):

# Enable EPEL repository
dnf install epel-release

# Install Ansible
dnf install ansible-core

# Or install full ansible package with extras
dnf install ansible

ansible --version

Control node installation (macOS):

# Using Homebrew
brew install ansible

# Or using pip (any platform)
pip3 install ansible

ansible --version

Control node installation (pip in virtualenv — recommended for isolation):

# Create dedicated environment
python3 -m venv ~/ansible-env
source ~/ansible-env/bin/activate

# Install Ansible
pip install ansible

# Install additional collections as needed
ansible-galaxy collection install community.general
ansible-galaxy collection install ansible.posix

Target node requirements:

Target servers need only Python 3 and SSH access. Most Linux distributions include both by default. Verify:

# On target server
python3 --version
# Python 3.x.x

# SSH must be accessible from control node
# Key-based authentication strongly recommended

Your First Inventory

The inventory defines which servers Ansible manages. Start with a simple INI-format file:

# inventory/hosts.ini
[webservers]
web01.example.com
web02.example.com
web03.example.com

[databases]
db01.example.com
db02.example.com

[monitoring]
prometheus.example.com

[switzerland:children]
webservers
databases
monitoring

Test connectivity to all hosts:

# Ping all hosts in inventory
ansible -i inventory/hosts.ini all -m ping

# Output:
# web01.example.com | SUCCESS => {
#     "changed": false,
#     "ping": "pong"
# }
# web02.example.com | SUCCESS => {
#     "changed": false,
#     "ping": "pong"
# }
# ...

Inventory with variables:

# inventory/hosts.ini
[webservers]
web01.example.com ansible_host=185.191.236.31 http_port=8080
web02.example.com ansible_host=185.191.236.32 http_port=8080
web03.example.com ansible_host=185.191.236.33 http_port=8081

[databases]
db01.example.com ansible_host=185.191.236.41 postgres_port=5432
db02.example.com ansible_host=185.191.236.42 postgres_port=5432 replica=true

[webservers:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3

[databases:vars]
ansible_user=dbadmin
backup_schedule=daily

YAML inventory (more flexible for complex setups):

# inventory/hosts.yml
all:
  children:
    webservers:
      hosts:
        web01.example.com:
          ansible_host: 185.191.236.31
          http_port: 8080
        web02.example.com:
          ansible_host: 185.191.236.32
          http_port: 8080
      vars:
        ansible_user: deploy
        nginx_worker_processes: auto
    
    databases:
      hosts:
        db01.example.com:
          ansible_host: 185.191.236.41
          role: primary
        db02.example.com:
          ansible_host: 185.191.236.42
          role: replica
      vars:
        ansible_user: dbadmin
        postgres_version: 16
    
    switzerland:
      children:
        webservers:
        databases:

Directory Structure for Production

Organize your Ansible project with a consistent structure that scales:

ansible-infrastructure/
├── ansible.cfg                 # Ansible configuration
├── inventory/
│   ├── production/
│   │   ├── hosts.yml          # Production inventory
│   │   ├── group_vars/
│   │   │   ├── all.yml        # Variables for all hosts
│   │   │   ├── webservers.yml # Variables for webservers group
│   │   │   └── databases.yml  # Variables for databases group
│   │   └── host_vars/
│   │       ├── web01.example.com.yml
│   │       └── db01.example.com.yml
│   └── staging/
│       ├── hosts.yml
│       └── group_vars/
│           └── all.yml
├── playbooks/
│   ├── site.yml               # Main playbook
│   ├── webservers.yml         # Web server configuration
│   ├── databases.yml          # Database configuration
│   └── security.yml           # Security hardening
├── roles/
│   ├── common/                # Base configuration role
│   ├── nginx/                 # Nginx role
│   ├── postgresql/            # PostgreSQL role
│   └── security/              # Security hardening role
└── files/
    └── ssh_keys/              # Public keys for deployment

ansible.cfg — Project configuration:

# ansible.cfg
[defaults]
inventory = inventory/production/hosts.yml
roles_path = roles
remote_user = deploy
private_key_file = ~/.ssh/ansible_deploy_key
host_key_checking = False
retry_files_enabled = False
stdout_callback = yaml
callbacks_enabled = profile_tasks

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

[ssh_connection]
pipelining = True
control_path = /tmp/ansible-%%h-%%p-%%r
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

Writing Playbooks

Playbooks define the tasks to execute on target hosts. They're YAML files with a specific structure:

# playbooks/webservers.yml
---
- name: Configure web servers
  hosts: webservers
  become: true
  
  vars:
    nginx_worker_connections: 4096
    app_root: /var/www/app
  
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600
    
    - name: Install required packages
      apt:
        name:
          - nginx
          - certbot
          - python3-certbot-nginx
          - htop
          - vim
        state: present
    
    - name: Create application directory
      file:
        path: "{{ app_root }}"
        state: directory
        owner: www-data
        group: www-data
        mode: '0755'
    
    - name: Deploy nginx configuration
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: '0644'
      notify: Reload nginx
    
    - name: Ensure nginx is running
      service:
        name: nginx
        state: started
        enabled: yes
  
  handlers:
    - name: Reload nginx
      service:
        name: nginx
        state: reloaded

Run the playbook:

# Run against all webservers
ansible-playbook playbooks/webservers.yml

# Run against specific host
ansible-playbook playbooks/webservers.yml --limit web01.example.com

# Dry run (check mode)
ansible-playbook playbooks/webservers.yml --check

# Show what would change (diff mode)
ansible-playbook playbooks/webservers.yml --check --diff

# Run with verbose output
ansible-playbook playbooks/webservers.yml -v   # or -vv, -vvv for more detail

Templates With Jinja2

Templates let you generate configuration files dynamically using variables from inventory or playbooks:

# templates/nginx.conf.j2
user www-data;
worker_processes {{ nginx_worker_processes | default('auto') }};
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections {{ nginx_worker_connections | default(1024) }};
    multi_accept on;
    use epoll;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Logging
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Gzip
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml application/json application/javascript;

    # Virtual hosts
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

# Server: {{ inventory_hostname }}
# Generated by Ansible on {{ ansible_date_time.iso8601 }}

Server block template with per-host variables:

# templates/vhost.conf.j2
server {
    listen {{ http_port | default(80) }};
    listen [::]:{{ http_port | default(80) }};
    server_name {{ server_name }};

{% if ssl_enabled | default(false) %}
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    
    ssl_certificate /etc/letsencrypt/live/{{ server_name }}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/{{ server_name }}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
{% endif %}

    root {{ app_root }};
    index index.html index.htm;

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

{% for location in custom_locations | default([]) %}
    location {{ location.path }} {
        {{ location.config | indent(8) }}
    }
{% endfor %}
}

Building Reusable Roles

Roles package related tasks, templates, files, and variables into reusable units. Create a role for common server baseline configuration:

# Create role structure
ansible-galaxy init roles/common

# roles/common/
# ├── defaults/
# │   └── main.yml      # Default variables (lowest priority)
# ├── files/            # Static files to copy
# ├── handlers/
# │   └── main.yml      # Handlers
# ├── meta/
# │   └── main.yml      # Role metadata and dependencies
# ├── tasks/
# │   └── main.yml      # Main task list
# ├── templates/        # Jinja2 templates
# └── vars/
#     └── main.yml      # Role variables (high priority)

roles/common/tasks/main.yml:

---
# Common baseline configuration for all servers

- name: Set timezone
  timezone:
    name: "{{ server_timezone | default('UTC') }}"

- name: Update apt cache
  apt:
    update_cache: yes
    cache_valid_time: 3600
  when: ansible_os_family == "Debian"

- name: Install essential packages
  apt:
    name: "{{ common_packages }}"
    state: present
  when: ansible_os_family == "Debian"

- name: Configure SSH daemon
  template:
    src: sshd_config.j2
    dest: /etc/ssh/sshd_config
    owner: root
    group: root
    mode: '0600'
    validate: 'sshd -t -f %s'
  notify: Restart sshd

- name: Deploy authorized SSH keys
  authorized_key:
    user: "{{ item.user }}"
    key: "{{ item.key }}"
    state: present
  loop: "{{ ssh_authorized_keys }}"
  when: ssh_authorized_keys is defined

- name: Configure sysctl parameters
  sysctl:
    name: "{{ item.name }}"
    value: "{{ item.value }}"
    state: present
    reload: yes
  loop: "{{ sysctl_settings }}"

- name: Configure automatic security updates
  apt:
    name: unattended-upgrades
    state: present
  when: ansible_os_family == "Debian"

- name: Enable unattended upgrades
  template:
    src: 20auto-upgrades.j2
    dest: /etc/apt/apt.conf.d/20auto-upgrades
    owner: root
    mode: '0644'
  when: ansible_os_family == "Debian"

roles/common/defaults/main.yml:

---
# Default variables for common role

server_timezone: UTC

common_packages:
  - vim
  - htop
  - curl
  - wget
  - git
  - net-tools
  - dnsutils
  - tcpdump
  - iotop
  - sysstat
  - jq
  - unzip
  - rsync
  - tree
  - fail2ban

sysctl_settings:
  - name: net.core.somaxconn
    value: "65535"
  - name: net.ipv4.tcp_max_syn_backlog
    value: "65535"
  - name: net.ipv4.ip_local_port_range
    value: "1024 65535"
  - name: vm.swappiness
    value: "10"
  - name: fs.file-max
    value: "2097152"

ssh_port: 22
ssh_permit_root_login: "prohibit-password"
ssh_password_authentication: "no"

roles/common/handlers/main.yml:

---
- name: Restart sshd
  service:
    name: sshd
    state: restarted

Using roles in playbooks:

# playbooks/site.yml
---
- name: Apply common configuration to all servers
  hosts: all
  become: true
  roles:
    - common

- name: Configure web servers
  hosts: webservers
  become: true
  roles:
    - nginx
    - certbot

- name: Configure database servers
  hosts: databases
  become: true
  roles:
    - postgresql
    - postgresql_backup

Managing Secrets With Ansible Vault

Never store passwords, API keys, or certificates in plain text. Ansible Vault encrypts sensitive data:

# Create an encrypted file
ansible-vault create inventory/production/group_vars/all/vault.yml

# Edit encrypted file (opens in $EDITOR)
ansible-vault edit inventory/production/group_vars/all/vault.yml

# View encrypted file without editing
ansible-vault view inventory/production/group_vars/all/vault.yml

# Encrypt existing file
ansible-vault encrypt secrets.yml

# Decrypt file
ansible-vault decrypt secrets.yml

# Change vault password
ansible-vault rekey vault.yml

Structure for vault variables:

# inventory/production/group_vars/all/vault.yml (encrypted)
---
vault_database_password: "super_secret_password_123"
vault_api_key: "sk-abc123def456"
vault_ssl_private_key: |
  -----BEGIN PRIVATE KEY-----
  MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...
  -----END PRIVATE KEY-----

# inventory/production/group_vars/all/main.yml (plain text)
---
# Reference vault variables with vault_ prefix
database_password: "{{ vault_database_password }}"
api_key: "{{ vault_api_key }}"
ssl_private_key: "{{ vault_ssl_private_key }}"

Running playbooks with vault:

# Prompt for vault password
ansible-playbook playbooks/site.yml --ask-vault-pass

# Use password file (for automation)
echo "your_vault_password" > ~/.vault_pass
chmod 600 ~/.vault_pass
ansible-playbook playbooks/site.yml --vault-password-file ~/.vault_pass

# Configure in ansible.cfg
# [defaults]
# vault_password_file = ~/.vault_pass

Encrypting individual strings:

# Encrypt a single value
ansible-vault encrypt_string 'my_secret_password' --name 'database_password'

# Output (paste into YAML):
# database_password: !vault |
#           $ANSIBLE_VAULT;1.1;AES256
#           61626364656667686970616263646566676869...

# Use in variable file
database_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          3137323466313534363866616462643261...

Conditional Execution and Loops

Real-world playbooks need logic for different scenarios:

# Conditionals
- name: Install nginx (Debian/Ubuntu)
  apt:
    name: nginx
    state: present
  when: ansible_os_family == "Debian"

- name: Install nginx (RHEL/CentOS)
  dnf:
    name: nginx
    state: present
  when: ansible_os_family == "RedHat"

# Multiple conditions
- name: Configure primary database
  template:
    src: postgresql-primary.conf.j2
    dest: /etc/postgresql/16/main/postgresql.conf
  when: 
    - role == "primary"
    - ansible_os_family == "Debian"

# Loops
- name: Create application users
  user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
    shell: /bin/bash
  loop:
    - { name: 'deploy', groups: 'www-data' }
    - { name: 'backup', groups: 'backup' }
    - { name: 'monitoring', groups: 'monitoring' }

# Loop with dictionary
- name: Configure virtual hosts
  template:
    src: vhost.conf.j2
    dest: "/etc/nginx/sites-available/{{ item.key }}.conf"
  loop: "{{ vhosts | dict2items }}"
  notify: Reload nginx

# Register results for later use
- name: Check if application is installed
  stat:
    path: /opt/myapp/bin/myapp
  register: app_binary

- name: Install application
  unarchive:
    src: "https://releases.example.com/myapp-{{ app_version }}.tar.gz"
    dest: /opt/myapp
    remote_src: yes
  when: not app_binary.stat.exists

Rolling Updates and Delegation

For production deployments, update servers in batches to maintain availability:

# playbooks/rolling-deploy.yml
---
- name: Rolling application deployment
  hosts: webservers
  become: true
  serial: 2  # Update 2 servers at a time
  max_fail_percentage: 25  # Abort if >25% fail
  
  pre_tasks:
    - name: Disable server in load balancer
      uri:
        url: "https://lb.example.com/api/servers/{{ inventory_hostname }}/disable"
        method: POST
        headers:
          Authorization: "Bearer {{ lb_api_token }}"
      delegate_to: localhost
    
    - name: Wait for connections to drain
      wait_for:
        timeout: 30
  
  roles:
    - application
  
  post_tasks:
    - name: Verify application health
      uri:
        url: "http://localhost:{{ http_port }}/health"
        status_code: 200
      retries: 5
      delay: 10
    
    - name: Re-enable server in load balancer
      uri:
        url: "https://lb.example.com/api/servers/{{ inventory_hostname }}/enable"
        method: POST
        headers:
          Authorization: "Bearer {{ lb_api_token }}"
      delegate_to: localhost

Delegation for tasks that run elsewhere:

# Run task on localhost (control node)
- name: Send deployment notification
  slack:
    token: "{{ slack_token }}"
    channel: "#deployments"
    msg: "Deployed {{ app_version }} to {{ inventory_hostname }}"
  delegate_to: localhost
  run_once: true  # Only send once, not per host

# Run task on a different host
- name: Update DNS record
  route53:
    zone: example.com
    record: "{{ inventory_hostname }}"
    type: A
    value: "{{ ansible_default_ipv4.address }}"
  delegate_to: dns-manager.example.com

Error Handling and Recovery

Production playbooks need robust error handling:

- name: Deploy with error handling
  hosts: webservers
  become: true
  
  tasks:
    - name: Create backup before deployment
      archive:
        path: /var/www/app
        dest: "/var/backups/app-{{ ansible_date_time.epoch }}.tar.gz"
      ignore_errors: yes  # Continue even if backup fails
    
    - name: Deploy new application version
      block:
        - name: Stop application
          service:
            name: myapp
            state: stopped
        
        - name: Deploy application files
          unarchive:
            src: "releases/myapp-{{ app_version }}.tar.gz"
            dest: /var/www/app
        
        - name: Run database migrations
          command: /var/www/app/bin/migrate
          register: migration_result
        
        - name: Start application
          service:
            name: myapp
            state: started
      
      rescue:
        - name: Deployment failed - rolling back
          debug:
            msg: "Deployment failed: {{ ansible_failed_result.msg | default('unknown error') }}"
        
        - name: Restore from backup
          unarchive:
            src: "/var/backups/app-{{ ansible_date_time.epoch }}.tar.gz"
            dest: /var/www/
            remote_src: yes
        
        - name: Start application with previous version
          service:
            name: myapp
            state: started
        
        - name: Fail playbook after rollback
          fail:
            msg: "Deployment failed and was rolled back"
      
      always:
        - name: Clean up old backups
          find:
            paths: /var/backups
            patterns: "app-*.tar.gz"
            age: 7d
          register: old_backups
        
        - name: Remove old backups
          file:
            path: "{{ item.path }}"
            state: absent
          loop: "{{ old_backups.files }}"

Dynamic Inventory for Cloud and APIs

For large or dynamic infrastructure, generate inventory programmatically:

# inventory/dynamic_inventory.py
#!/usr/bin/env python3
import json
import subprocess

def get_servers_from_api():
    # Example: fetch from your infrastructure API
    # In production, call your CMDB, cloud API, or Terraform state
    servers = {
        "webservers": {
            "hosts": ["web01.example.com", "web02.example.com"],
            "vars": {
                "http_port": 8080
            }
        },
        "databases": {
            "hosts": ["db01.example.com"],
            "vars": {
                "postgres_version": 16
            }
        },
        "_meta": {
            "hostvars": {
                "web01.example.com": {
                    "ansible_host": "185.191.236.31"
                },
                "web02.example.com": {
                    "ansible_host": "185.191.236.32"
                }
            }
        }
    }
    return servers

if __name__ == "__main__":
    print(json.dumps(get_servers_from_api()))

# Make executable and use
# chmod +x inventory/dynamic_inventory.py
# ansible-playbook -i inventory/dynamic_inventory.py playbooks/site.yml

AWS EC2 dynamic inventory:

# Install AWS collection
ansible-galaxy collection install amazon.aws

# inventory/aws_ec2.yml
---
plugin: amazon.aws.aws_ec2
regions:
  - eu-central-1
  - eu-west-1

filters:
  tag:Environment: production
  instance-state-name: running

keyed_groups:
  - key: tags.Role
    prefix: role
  - key: placement.availability_zone
    prefix: az

hostnames:
  - private-ip-address

compose:
  ansible_host: private_ip_address

# Use with: ansible-inventory -i inventory/aws_ec2.yml --graph

Performance Optimization

Speed up Ansible execution on large fleets:

# ansible.cfg optimizations
[defaults]
forks = 50                      # Parallel connections (default 5)
gathering = smart               # Cache facts between plays
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts_cache
fact_caching_timeout = 86400    # 24 hours

[ssh_connection]
pipelining = True               # Reduces SSH operations
control_path = /tmp/ansible-%%h-%%p-%%r
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o PreferredAuthentications=publickey

Async tasks for long-running operations:

- name: Run long database backup
  command: /usr/local/bin/full-backup.sh
  async: 3600      # Maximum runtime (1 hour)
  poll: 0          # Don't wait for completion
  register: backup_job

- name: Continue with other tasks
  debug:
    msg: "Backup running in background"

- name: Check backup completion
  async_status:
    jid: "{{ backup_job.ansible_job_id }}"
  register: job_result
  until: job_result.finished
  retries: 60
  delay: 60

Strategy plugins for execution control:

# Linear (default) - one task at a time across all hosts
- hosts: webservers
  strategy: linear
  tasks: [...]

# Free - each host runs independently as fast as possible
- hosts: webservers
  strategy: free
  tasks: [...]

# Host pinned - like free but maintains host ordering
- hosts: webservers
  strategy: host_pinned
  tasks: [...]

Testing With Molecule

Test roles before deploying to production:

# Install Molecule with Docker driver
pip install molecule molecule-plugins[docker]

# Initialize testing for existing role
cd roles/nginx
molecule init scenario --driver-name docker

# roles/nginx/molecule/default/
# ├── converge.yml     # Apply the role
# ├── molecule.yml     # Test configuration
# └── verify.yml       # Verification tests

molecule/default/molecule.yml:

---
dependency:
  name: galaxy
driver:
  name: docker
platforms:
  - name: ubuntu-jammy
    image: ubuntu:22.04
    pre_build_image: false
    privileged: true
    command: /lib/systemd/systemd
  - name: rocky-9
    image: rockylinux:9
    pre_build_image: false
    privileged: true
    command: /lib/systemd/systemd
provisioner:
  name: ansible
verifier:
  name: ansible

molecule/default/verify.yml:

---
- name: Verify nginx installation
  hosts: all
  gather_facts: false
  tasks:
    - name: Check nginx is installed
      package:
        name: nginx
        state: present
      check_mode: true
      register: nginx_installed
    
    - name: Assert nginx is installed
      assert:
        that:
          - not nginx_installed.changed
        fail_msg: "Nginx is not installed"
    
    - name: Check nginx is running
      service:
        name: nginx
        state: started
      check_mode: true
      register: nginx_running
    
    - name: Assert nginx is running
      assert:
        that:
          - not nginx_running.changed
        fail_msg: "Nginx is not running"
    
    - name: Verify nginx responds
      uri:
        url: http://localhost
        status_code: [200, 301, 302]
# Run tests
molecule test

# Step through testing
molecule create      # Create test instances
molecule converge    # Apply role
molecule verify      # Run verification
molecule destroy     # Clean up

Integrating With CI/CD

Automate Ansible runs in your deployment pipeline:

# .gitlab-ci.yml
stages:
  - lint
  - test
  - deploy

variables:
  ANSIBLE_HOST_KEY_CHECKING: "False"

ansible-lint:
  stage: lint
  image: cytopia/ansible-lint
  script:
    - ansible-lint playbooks/

molecule-test:
  stage: test
  image: docker:latest
  services:
    - docker:dind
  before_script:
    - pip install ansible molecule molecule-plugins[docker]
  script:
    - cd roles/nginx && molecule test

deploy-staging:
  stage: deploy
  image: cytopia/ansible
  script:
    - echo "$VAULT_PASSWORD" > .vault_pass
    - chmod 600 .vault_pass
    - ansible-playbook -i inventory/staging/hosts.yml playbooks/site.yml
  environment:
    name: staging
  only:
    - develop

deploy-production:
  stage: deploy
  image: cytopia/ansible
  script:
    - echo "$VAULT_PASSWORD" > .vault_pass
    - chmod 600 .vault_pass
    - ansible-playbook -i inventory/production/hosts.yml playbooks/site.yml
  environment:
    name: production
  only:
    - main
  when: manual

Fleet Management Patterns

Practical patterns for managing Swiss dedicated server fleets:

Server provisioning workflow:

# playbooks/provision-new-server.yml
---
- name: Provision new server
  hosts: "{{ target_host }}"
  become: true
  
  vars_prompt:
    - name: target_host
      prompt: "Enter hostname of new server"
      private: no
  
  pre_tasks:
    - name: Wait for server to be reachable
      wait_for_connection:
        timeout: 300
    
    - name: Gather facts
      setup:
  
  roles:
    - common
    - security
    - monitoring-agent
  
  post_tasks:
    - name: Add to monitoring system
      uri:
        url: "https://monitoring.example.com/api/hosts"
        method: POST
        body_format: json
        body:
          hostname: "{{ inventory_hostname }}"
          ip: "{{ ansible_default_ipv4.address }}"
      delegate_to: localhost
    
    - name: Send provisioning notification
      slack:
        token: "{{ slack_token }}"
        channel: "#infrastructure"
        msg: "Server {{ inventory_hostname }} provisioned successfully"
      delegate_to: localhost

Security audit across fleet:

# playbooks/security-audit.yml
---
- name: Security audit
  hosts: all
  become: true
  gather_facts: yes
  
  tasks:
    - name: Check for password authentication in SSH
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^PasswordAuthentication'
        line: 'PasswordAuthentication no'
      check_mode: yes
      register: ssh_password_check
    
    - name: Check firewall is active
      command: ufw status
      register: ufw_status
      changed_when: false
      failed_when: false
    
    - name: Check for pending security updates
      command: apt list --upgradable
      register: pending_updates
      changed_when: false
      when: ansible_os_family == "Debian"
    
    - name: Generate audit report
      template:
        src: audit-report.j2
        dest: "/tmp/audit-{{ inventory_hostname }}.txt"
      delegate_to: localhost
    
    - name: Collect audit reports
      fetch:
        src: "/tmp/audit-{{ inventory_hostname }}.txt"
        dest: "reports/security-audit/"
        flat: yes
      delegate_to: localhost

Emergency patching:

# playbooks/emergency-patch.yml
---
- name: Emergency security patch
  hosts: all
  become: true
  serial: "{{ batch_size | default('20%') }}"
  
  vars:
    package_name: "{{ target_package }}"
  
  tasks:
    - name: Check current package version
      package_facts:
        manager: auto
    
    - name: Show current version
      debug:
        msg: "Current {{ package_name }}: {{ ansible_facts.packages[package_name][0].version | default('not installed') }}"
    
    - name: Apply security update
      apt:
        name: "{{ package_name }}"
        state: latest
        only_upgrade: yes
      register: update_result
      when: ansible_os_family == "Debian"
    
    - name: Restart affected services if needed
      service:
        name: "{{ item }}"
        state: restarted
      loop: "{{ restart_services | default([]) }}"
      when: update_result.changed

# Run: ansible-playbook playbooks/emergency-patch.yml -e "target_package=openssl restart_services=['nginx','postgresql']"

Production Checklist

Before deploying Ansible automation to production on your Swiss VPS or dedicated infrastructure:

Security:

• All secrets in Ansible Vault, never plain text
• Vault password stored securely (not in git)
• SSH keys rotated regularly
• Principle of least privilege for ansible user
• Audit logging enabled on control node

Code quality:

• All playbooks pass ansible-lint
• Roles tested with Molecule
• README.md documents each role
• Variables documented in defaults/main.yml
• Handlers used for service restarts

Operations:

• Playbooks tested in staging before production
• Rolling updates configured for critical services
• Rollback procedures documented and tested
• Change notifications sent to team channels
• Execution logs retained for audit

Version control:

• All Ansible code in git
• Meaningful commit messages
• Branch protection for production inventory
• Tags for major releases
• .gitignore excludes sensitive files

Conclusion

Ansible transforms server management from artisanal SSH sessions into reliable, repeatable, version-controlled automation. The initial investment in writing playbooks and roles pays dividends every time you need to deploy, update, audit, or recover your infrastructure.

Start small. Pick one repetitive task — maybe SSH hardening or package updates — and automate it. Once you see one playbook save hours of manual work, you'll want to automate everything. The key is building incrementally: a common role for baseline configuration, then specialized roles for each service, then orchestration playbooks that tie everything together.

For fleets of Swiss dedicated servers, Ansible provides the consistency and auditability that manual management can never achieve. Every server configured identically. Every change tracked in git. Every deployment repeatable. That's how you operate infrastructure at scale without it becoming unmanageable.