Setting Up an Ansible Server for Automated Ubuntu Management in 2025

Introduction

If you’re like me, constantly repeating the same tasks or struggling to stay focused on routine maintenance, it’s time for a fresh start. That’s why I’ve decided to wipe all my VMs and rebuild my home lab from scratch in 2025.

The first step in my new setup? Deploying an Ansible server to automate system management. I’ll be storing my playbooks on GitHub, making them available as templates for others. Feel free to share your thoughts, feedback, or suggestions!

Ansible is an open-source IT automation and configuration management tool that allows you to automate repetitive tasks, manage configurations, and orchestrate complex deployments across multiple servers. It is known for its agentless architecture, meaning you don’t have to install any special software on the nodes you manage—just ensure they have SSH (Linux/Unix) or WinRM (Windows) enabled.

Why Ansible?

  • Efficiency: Automate updates, upgrades, and system maintenance.
  • Scalability: Manage multiple machines with a single command.
  • Rollback Safety: With VM snapshots, I can test, rewind, fix, and retry without fear.

What Can Ansible Do for an IT System Administrator?

  1. Configuration Management
    • Define your desired system state (e.g., packages, services, config files) in Playbooks (written in YAML), and Ansible ensures each system matches that configuration.
    • It’s repeatable: once you define the playbooks, you can use them multiple times to enforce consistency.
  2. Provisioning and Deployment
    • Quickly spin up new servers (physical, virtual, or cloud) with pre-installed packages, user accounts, and security configurations.
    • Deploy applications and services in a standardized manner.
  3. Orchestration
    • Coordinate tasks across multiple systems, such as performing a rolling update or orchestrating a multi-tier service launch.
    • Automate interdependent tasks (like updating DNS, load balancers, and web servers in a predictable sequence).
  4. Security and Compliance
    • Automate patch management to keep your fleet of servers up to date.
    • Enforce security best practices, like ensuring firewalls are correctly configured, SSH keys are in place, etc.
  5. Agentless and Simple
    • No extra agent software needed on managed nodes—just SSH.
    • Playbooks are written in a human-readable YAML syntax, making them easy to learn and maintain.

What Can Ansible Do for an SAP Basis Administrator?

For SAP Basis teams, Ansible can streamline the maintenance and configuration of SAP environments by automating tasks that are typically manual and time-consuming:

  1. Automated System Setup
    • Install and configure the necessary infrastructure for SAP systems (OS packages, kernel parameters, etc.).
    • Ensure consistent setups across Development, QA, and Production environments.
  2. System Patching and Updates
    • Handle both OS-level patches and SAP-related patches in a controlled, repeatable way.
    • Automate the sequence of tasks needed before and after patching (e.g., backups, stopping services, clearing cache).
  3. SAP Transport Management
    • Integrate with SAP’s built-in transport tools to automatically move transports between environments.
    • Orchestrate approvals, apply changes, and roll them back if needed.
  4. User and Security Management
    • Automate the creation and maintenance of users, roles, and profiles in SAP landscapes.
    • Enforce security policies uniformly across the environment.
  5. Monitoring and Housekeeping Tasks
    • Schedule and automate regular cleanup jobs (e.g., deleting old logs, archiving data).
    • Integrate with monitoring solutions to automatically react to events or thresholds.
  6. Faster Provisioning of SAP Systems
    • Spin up new SAP systems (e.g., sandboxes for testing or training) more quickly.
    • Pre-configure them with roles, services, and monitoring tools.

Key Takeaways

  • IT System Admins benefit from simplified configuration management, patching, and deployments.
  • SAP Basis Admins can automate system provisioning, patching, transport management, and environment consistency checks.

Whether you’re managing a handful of servers or a large SAP landscape, Ansible helps reduce manual effort, minimize errors, and ensure uniformity across all systems—ultimately allowing you to focus on more strategic tasks.

Let’s start by installing Ansible and setting up our first playbooks.

Step 1: Prepare the System

Before installing Ansible, ensure your system is up to date:

sudo apt update && sudo apt upgrade -y
sudo reboot

This ensures a clean slate before proceeding with Ansible installation.

Step 2: Install Ansible

Install Ansible along with sshpass (required for password-based SSH authentication):

sudo apt install -y ansible sshpass

Verify that Ansible is installed correctly:

ansible --version

Step 3: Set Up the Ansible Inventory (Hosts File)

Ansible uses an inventory file to define which machines it manages. Organize it based on OS, environment (DEV, QLT), or your preferred structure.

Create the Inventory Folder

mkdir -p inventory playbook
vi ./inventory/hosts

Example hosts File

[ubuntu]
prometheus
zabbix
demo
ansible
wazuh

This defines a group of Ubuntu-based servers that Ansible will manage.


Step 4: Test Ansible Connectivity

To avoid SSH key verification issues, disable host key checking temporarily and test Ansible’s connectivity:

export ANSIBLE_HOST_KEY_CHECKING=False
ansible -i ./inventory/hosts ubuntu -m ping --user system --ask-pass

Expected Output:

If successful, you should see:

ansible | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

Step 5: Create and Run Ansible Playbooks

Now, let’s create our first playbooks.

Playbook 1: Ubuntu Update & Cleanup (ubuntuUpdate.yml)

This playbook updates all Ubuntu servers, upgrades installed packages, and removes unnecessary ones.

Create the Playbook File

vi ./playbook/ubuntuUpdate.yml

Playbook Contents

- name: Update all Ubuntu servers
  hosts: ubuntu
  become: yes  # Run as root
  tasks:
    - name: Update package list
      apt:
        update_cache: yes

    - name: Upgrade all packages
      apt:
        upgrade: dist  # Perform a full system upgrade

    - name: Remove unnecessary packages
      apt:
        autoremove: yes
        autoclean: yes

Run the Playbook

ansible-playbook ./playbook/ubuntuUpdate.yml --user system --ask-pass --ask-become-pass -i ./inventory/hosts

Playbook 2: Update Ubuntu & Install QEMU Guest Agent (update_and_install_qemu.yml)

This playbook updates Ubuntu, installs the QEMU Guest Agent, ensures it is enabled, and reboots the system if necessary.

Create the Playbook File

vi ./playbook/update_and_install_qemu.yml

Playbook Contents

- name: Update Ubuntu servers and install QEMU Guest Agent
  hosts: ubuntu
  become: yes  # Run as root
  tasks:
    - name: Update package list
      apt:
        update_cache: yes

    - name: Upgrade all packages
      apt:
        upgrade: dist  # Perform a full system upgrade

    - name: Install QEMU Guest Agent
      apt:
        name: qemu-guest-agent
        state: present

    - name: Ensure QEMU Guest Agent is enabled and running
      systemd:
        name: qemu-guest-agent
        enabled: yes
        state: started

    - name: Remove unnecessary packages
      apt:
        autoremove: yes
        autoclean: yes

    - name: Check if a reboot is required
      register: reboot_required
      stat:
        path: /var/run/reboot-required
      changed_when: false

    - name: Reboot if required
      reboot:
      when: reboot_required.stat.exists

Run the Playbook

ansible-playbook ./playbook/update_and_install_qemu.yml --user system --ask-pass --ask-become-pass -i ./inventory/hosts

Playbook Execution Results

When executed successfully, you should see output like this:

PLAY RECAP ****************************************************************************************************************************
ansible                    : ok=7    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
demo                       : ok=7    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
prometheus                 : ok=7    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
wazuh                      : ok=7    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
zabbix                     : ok=7    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

This confirms that Ansible successfully ran all tasks across the listed Ubuntu servers.


Bonus Section: Useful Ansible Playbooks

In this bonus section, I’m including two essential Ansible playbooks that can help streamline system administration tasks. These playbooks focus on granting passwordless sudo access to a specific user and automating SSH key distribution across multiple hosts.

1. Granting Passwordless Sudo Access to the ‘system’ User

This playbook ensures that the ‘system’ user has passwordless sudo access by adding an entry to the /etc/sudoers.d/system file. This is useful when automating administrative tasks without requiring manual password input.

Playbook: updateSudoers.yml

- name: Grant passwordless sudo access to 'system' user
  hosts: all
  become: yes
  tasks:
    - name: Ensure 'system' user is in the sudoers file with NOPASSWD
      copy:
        dest: "/etc/sudoers.d/system"
        content: "system ALL=(ALL) NOPASSWD: ALL"
        mode: '0440'

How It Works:

  • The playbook runs on all targeted hosts.
  • It ensures the system user can execute commands as sudo without requiring a password.
  • The copy module creates a new sudoers file under /etc/sudoers.d/, preventing any direct modifications to the main /etc/sudoers file.

2. Automating SSH Key Distribution

This playbook automates the generation and distribution of SSH keys, allowing passwordless SSH access between an Ansible control node and its target hosts. This is particularly useful for managing multiple systems securely and efficiently.

Playbook: sshKey.yml

---
- name: Generate and exchange SSH keys with target hosts
  hosts: all
  become: false
  gather_facts: no

  tasks:
    - name: Check if SSH key already exists on Ansible control node
      delegate_to: localhost
      stat:
        path: "~/.ssh/id_rsa.pub"
      register: ssh_key_check

    - name: Generate SSH key on Ansible control node (if not exists)
      delegate_to: localhost
      command: ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N ""
      when: not ssh_key_check.stat.exists

    - name: Fetch the public key
      delegate_to: localhost
      slurp:
        src: "~/.ssh/id_rsa.pub"
      register: ssh_public_key

    - name: Ensure .ssh directory exists on the target hosts
      file:
        path: "~/.ssh"
        state: directory
        mode: '0700'

    - name: Add the public key to authorized_keys
      copy:
        content: "{{ ssh_public_key.content | b64decode }}"
        dest: "~/.ssh/authorized_keys"
        mode: '0600'

How It Works:

  • The playbook first checks if an SSH key already exists on the Ansible control node.
  • If no key exists, it generates a new RSA key pair.
  • The public key is then retrieved and distributed to all target hosts, ensuring passwordless SSH access.
  • The .ssh directory is created if it doesn’t already exist on the target machines.
  • The public key is appended to the authorized_keys file, enabling secure authentication.

Running the Playbooks Without Password Prompt

Once the above configurations are in place, you can run the Ansible playbooks without requiring a password (example):

ansible-playbook -i inventory updateSudoers.yml
ansible-playbook -i inventory sshKey.yml

If using a specific user, ensure the command is executed as:

ansible-playbook -i inventory -u system updateSudoers.yml
ansible-playbook -i inventory -u system sshKey.yml

This ensures that all configurations are applied seamlessly without requiring manual password input.

Why These Playbooks Matter

  • Security & Efficiency: Passwordless sudo and SSH access reduce manual intervention and improve automation reliability.
  • Consistency: Using Ansible ensures that all systems follow the same configuration policies.
  • Scalability: Easily manage multiple servers without the hassle of manual SSH key exchanges or sudo permissions setup.

By including these playbooks in your automation toolkit, you can significantly enhance your workflow and system administration efficiency.

Conclusion

With Ansible set up, managing multiple servers becomes faster, easier, and more consistent. Playbooks allow for repeatable automation, reducing manual errors and ensuring a standardized environment.

Next Steps

  • Store your Ansible playbooks on GitHub for easy access and collaboration.
  • Experiment with more advanced playbooks for software deployment and security hardening.
  • Consider integrating Ansible Tower or AWX for a GUI-based management experience.

Let me know if you have any feedback or ideas for improving these playbooks. Happy automation! 🚀

Similar Posts