RHEL BasedRocky Linux

How To Install Ansible on Rocky Linux 10

Install Ansible on Rocky Linux 10

Automation has become the cornerstone of modern IT infrastructure management, enabling organizations to streamline complex workflows and reduce manual intervention. Ansible stands out as a powerful open-source automation tool that simplifies configuration management, application deployment, and orchestration tasks across diverse environments. Rocky Linux 10, an enterprise-grade Linux distribution that provides a stable RHEL alternative, offers an ideal platform for deploying Ansible-based automation solutions. This comprehensive guide walks through the complete installation and configuration process, ensuring a robust foundation for infrastructure automation.

The agentless architecture of Ansible makes it particularly attractive for Rocky Linux environments, as it relies solely on SSH connections without requiring agent software on managed nodes. This design philosophy reduces overhead, simplifies maintenance, and enhances security across distributed systems.

What is Ansible?

Ansible is an open-source automation platform that enables infrastructure as code practices through human-readable YAML playbooks. Developed by Red Hat, it provides a declarative approach to configuration management, allowing administrators to define desired system states rather than scripting procedural steps. The architecture consists of control nodes where Ansible runs and managed nodes that receive configuration instructions via SSH.

Unlike traditional configuration management tools, Ansible operates without agents on target systems. This agentless design eliminates the complexity of maintaining additional software across infrastructure while reducing potential security vulnerabilities. The platform uses modules—small programs that execute specific tasks—to manage everything from package installation to cloud resource provisioning.

Ansible’s core components include playbooks for defining automation workflows, inventory files for organizing managed hosts, roles for packaging reusable automation content, and collections that bundle related modules and plugins. These elements work together to create scalable, maintainable automation solutions. Common use cases span server provisioning, application deployment, network device configuration, security compliance enforcement, and cloud infrastructure orchestration.

Prerequisites and System Requirements

Before installing Ansible on Rocky Linux 10, several foundational requirements must be met to ensure smooth deployment. The control node—the system where Ansible will be installed—requires Python 3.9 or newer to support current Ansible versions. Managed nodes need Python 2.7 or Python 3.5+ installed, though Python 3 is strongly recommended for security and compatibility reasons.

Root or sudo privileges are essential on the control node for installation and configuration tasks. SSH access must be configured between the control node and all managed hosts, as Ansible relies exclusively on SSH for communication. Network connectivity on port 22 (default SSH port) should be verified across all systems in the inventory.

For testing purposes, at least two Rocky Linux 10 systems are recommended—one serving as the control node and one or more as managed nodes. This setup allows practical verification of Ansible functionality. Basic command-line proficiency is assumed, including familiarity with text editors like vi or nano, file system navigation, and package management concepts.

Firewall configurations may require adjustment to permit SSH traffic between control and managed nodes. SELinux policies should also be considered, though default configurations typically accommodate Ansible operations. Adequate disk space—approximately 300MB for the full Ansible package and its dependencies—ensures successful installation.

Understanding Installation Methods

Rocky Linux 10 offers two primary approaches for installing Ansible, each with distinct advantages depending on deployment requirements. The DNF package manager method provides system-wide installation with automatic dependency resolution and simplified updates through the operating system’s package management infrastructure. This approach installs Ansible from the AppStream repository, which has included Ansible packages natively since Rocky Linux 9.

The pip installation method uses Python’s package installer to deploy Ansible directly from the Python Package Index (PyPI). This approach offers access to the latest upstream releases immediately, providing more granular version control and the ability to install Ansible in user space without requiring system-wide privileges. The official Ansible documentation recommends pip as the preferred installation method for production environments.

Two package variants exist regardless of installation method: the full ansible package includes ansible-core plus a curated collection of commonly used modules and plugins, while ansible-core provides only the core functionality with minimal additional content. Most users benefit from the complete ansible package, which includes essential modules for managing Linux systems, cloud platforms, and network devices out of the box.

Method 1: Installing Ansible via DNF

Updating System Packages

Begin by updating all existing packages on the Rocky Linux 10 control node to ensure compatibility and incorporate the latest security patches. Execute the following command with sudo privileges:

sudo dnf update -y

This command synchronizes package repositories, identifies available updates, and applies them automatically with the -y flag confirming all prompts. The update process typically completes within a few minutes depending on system specifications and network bandwidth. A system reboot may be recommended if kernel updates are included.

Installing Ansible from AppStream Repository

Rocky Linux 10 includes Ansible packages in the default AppStream repository, eliminating the need for additional repository configuration. Install the complete Ansible package with the following command:

sudo dnf install ansible -y

DNF automatically resolves dependencies, downloading and installing Python libraries, SSH clients, and supporting utilities required for Ansible operation. The installation process displays progress indicators and confirms successful completion.

For environments requiring only core Ansible functionality without the extended module collections, install the minimal package instead:

sudo dnf install ansible-core -y

The ansible-core package consumes less disk space and provides faster installation, though additional modules must be installed separately as needed through Ansible Galaxy or pip. This approach suits containerized deployments or highly customized automation environments where precise control over included components is required.

Package installation places configuration files in /etc/ansible/, executables in /usr/bin/, and Python modules in system library directories. The DNF method ensures these files integrate properly with Rocky Linux’s file system hierarchy and security policies.

Verifying DNF Installation

Confirm successful installation by checking the Ansible version:

ansible --version

This command displays comprehensive version information including the Ansible core version, configuration file location, module search paths, Python version in use, and executable location. A typical output shows ansible-core 2.14 or newer on Rocky Linux 10 systems.

Verify the installation path and available modules:

which ansible
ansible-doc -l | head -20

The first command confirms the ansible executable location, while the second lists available modules. The ansible-doc command provides invaluable reference documentation for all installed modules, accessible directly from the command line.

Check installed Ansible collections, which are packages of related modules, plugins, and roles:

ansible-galaxy collection list

This command enumerates all collections included with the installation. The full Ansible package typically includes collections for cloud providers, network devices, and system administration tasks.

Method 2: Installing Ansible via pip

Installing Python pip Package Manager

Python’s pip package manager must be installed before proceeding with Ansible installation via this method. Rocky Linux 10 includes Python 3 by default, but pip may require separate installation:

sudo dnf install python3-pip -y

Verify pip installation and upgrade to the latest version:

pip3 --version
pip3 install --upgrade pip --user

The --user flag installs the pip upgrade in the user’s home directory rather than system-wide, avoiding potential conflicts with system-managed packages. Updated pip versions include performance improvements and security enhancements.

Installing Required Python Dependencies

Ansible requires specific Python dependencies that may not be present on a fresh Rocky Linux 10 installation. Install these prerequisites:

pip3 install setuptools-rust wheel --user

The setuptools-rust package enables compilation of Rust-based Python extensions, while wheel provides support for binary package distribution format. These dependencies ensure Ansible and its related packages install correctly without compilation errors.

Installing Ansible Using pip

Install the complete Ansible package using pip3:

pip3 install ansible --user

This command downloads Ansible from the Python Package Index and installs it in the user’s home directory under ~/.local/. Installation time varies based on network speed but typically completes within a few minutes. The output displays download progress and confirms successful installation of Ansible and all dependencies.

For minimal installations requiring only ansible-core:

pip3 install ansible-core --user

Pip offers precise version control, allowing installation of specific Ansible releases when compatibility requirements dictate:

pip3 install ansible==2.14.0 --user

This capability proves invaluable in enterprise environments where automation code has been validated against specific Ansible versions.

After pip installation, update the PATH environment variable if necessary. Add the following line to ~/.bashrc or ~/.bash_profile:

export PATH="$HOME/.local/bin:$PATH"

Source the file to apply changes immediately:

source ~/.bashrc

Verify the installation:

ansible --version

The output confirms Ansible is accessible and displays configuration details.

Configuring Ansible on Rocky Linux 10

Understanding ansible.cfg Configuration File

Ansible’s behavior is governed by the ansible.cfg configuration file, which controls defaults for connection parameters, privilege escalation, logging, and performance tuning. Ansible searches for configuration files in a specific order: the ANSIBLE_CONFIG environment variable, ansible.cfg in the current directory, ~/.ansible.cfg in the user’s home directory, and finally /etc/ansible/ansible.cfg as the system-wide default.

When installing via DNF, the system-wide configuration file is created automatically at /etc/ansible/ansible.cfg. Pip installations require manual creation. Generate a comprehensive sample configuration file:

ansible-config init --disabled > ansible.cfg

This command creates a configuration file with all available options commented out, serving as an excellent reference. For a minimal configuration with only defaults, omit the --disabled flag.

Before modifying the system configuration, create a backup:

sudo cp /etc/ansible/ansible.cfg /etc/ansible/ansible.cfg.backup

The configuration file is organized into sections, each controlling different aspects of Ansible operation. The [defaults] section contains the most commonly modified settings.

Customizing Key Configuration Settings

Open the configuration file with a text editor:

sudo nano /etc/ansible/ansible.cfg

Modify essential settings for optimal Rocky Linux 10 operation. Disable host key checking to simplify initial setup, though this reduces security for production environments:

[defaults]
host_key_checking = False

Configure the default inventory file location:

inventory = /etc/ansible/hosts

Set the default remote user for SSH connections:

remote_user = ansible

Configure privilege escalation settings:

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

These settings enable automatic privilege escalation using sudo without password prompts, requiring passwordless sudo configuration for the ansible user.

Optimize SSH connection performance:

[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

Pipelining reduces the number of SSH operations required, significantly improving performance for playbooks with many tasks. ControlMaster enables SSH connection multiplexing, reusing established connections for subsequent operations.

Configure logging for troubleshooting and audit purposes:

[defaults]
log_path = /var/log/ansible.log

Ensure the log directory exists and the ansible user has write permissions.

Creating Project-Specific Configuration

Best practices recommend maintaining project-specific ansible.cfg files rather than relying solely on system-wide configuration. Create a dedicated directory for Ansible projects:

mkdir ~/ansible-projects
cd ~/ansible-projects
nano ansible.cfg

Create a minimal project-specific configuration:

[defaults]
inventory = ./inventory
remote_user = ansible
host_key_checking = False

[privilege_escalation]
become = True
become_method = sudo

Ansible uses the configuration file in the current directory with highest priority, allowing project-specific overrides without affecting other automation workflows. Store project configurations in version control systems like Git for team collaboration and change tracking.

Setting Up SSH Key Authentication

Generating SSH Key Pairs

Ansible relies on SSH key-based authentication for secure, passwordless connections to managed nodes. Generate an SSH key pair on the control node:

ssh-keygen -t ed25519 -C "ansible-control"

The ED25519 algorithm provides strong security with excellent performance. Alternatively, use RSA with 4096-bit keys:

ssh-keygen -t rsa -b 4096 -C "ansible-control"

When prompted for a file location, accept the default (~/.ssh/id_ed25519 or ~/.ssh/id_rsa). The passphrase prompt offers additional security—enter a passphrase for environments requiring defense-in-depth, or press Enter for passwordless operation suitable for automated workflows.

The command generates two files: a private key (keep secure, never share) and a public key (with .pub extension, safe to distribute). Verify key generation:

ls -la ~/.ssh/

Set restrictive permissions on the private key:

chmod 600 ~/.ssh/id_ed25519

Distributing SSH Keys to Managed Nodes

Copy the public key to each managed node using ssh-copy-id:

ssh-copy-id ansible@managed-node-1
ssh-copy-id ansible@managed-node-2

Replace ansible with the appropriate remote username and managed-node-1 with the actual hostname or IP address. The command prompts for the remote user’s password, then copies the public key to ~/.ssh/authorized_keys on the managed node.

For environments with many hosts, use a loop:

for host in node1 node2 node3; do
    ssh-copy-id ansible@$host
done

Test passwordless SSH connection:

ssh ansible@managed-node-1

If configured correctly, the connection succeeds without password prompts. Exit the SSH session and return to the control node.

SSH Configuration Best Practices

Create an SSH configuration file to simplify connections:

nano ~/.ssh/config

Add host entries:

Host managed-node-1
    HostName 192.168.1.101
    User ansible
    IdentityFile ~/.ssh/id_ed25519

Host managed-node-2
    HostName 192.168.1.102
    User ansible
    IdentityFile ~/.ssh/id_ed25519

This configuration allows simple connections using ssh managed-node-1 instead of full connection strings. For enhanced security, disable password authentication on managed nodes after confirming key-based authentication works correctly. Edit /etc/ssh/sshd_config on managed nodes:

PasswordAuthentication no
PubkeyAuthentication yes

Restart the SSH service:

sudo systemctl restart sshd

Regular key rotation enhances security—generate new keys annually or when personnel changes occur.

Creating and Managing Ansible Inventory

Understanding Inventory Files

Ansible inventory files define the hosts and groups that automation targets. The inventory serves as the source of truth for infrastructure topology, organizing systems into logical groups for efficient management. Default inventory location is /etc/ansible/hosts, though project-specific inventories are recommended.

Inventory files support two primary formats: INI-style (simple, human-readable) and YAML (structured, supports complex hierarchies). Static inventories list hosts explicitly, while dynamic inventories query external sources like cloud providers or CMDBs for real-time host information.

Creating a Basic Inventory File

Create a simple INI-format inventory:

sudo nano /etc/ansible/hosts

Add host definitions:

[webservers]
web1 ansible_host=192.168.1.101
web2 ansible_host=192.168.1.102

[databases]
db1 ansible_host=192.168.1.201
db2 ansible_host=192.168.1.202

[production:children]
webservers
databases

This inventory defines two host groups (webservers and databases) and a parent group (production) containing both. The ansible_host variable maps aliases to IP addresses or hostnames.

For YAML format, create an equivalent inventory:

all:
  children:
    webservers:
      hosts:
        web1:
          ansible_host: 192.168.1.101
        web2:
          ansible_host: 192.168.1.102
    databases:
      hosts:
        db1:
          ansible_host: 192.168.1.201
        db2:
          ansible_host: 192.168.1.202
    production:
      children:
        - webservers
        - databases

YAML format supports more complex structures and integrates well with modern infrastructure-as-code practices.

Advanced Inventory Concepts

Use ranges for multiple similar hosts:

[webservers]
web[01:10] ansible_host=192.168.1.[101:110]

This creates entries for web01 through web10 with corresponding IP addresses. Set variables at group level using group_vars directories:

mkdir -p group_vars
nano group_vars/webservers.yml

Add group-specific variables:

---
http_port: 80
max_clients: 200

Variables in group_vars/webservers.yml apply to all hosts in the webservers group. Host-specific variables use host_vars directories with similar structure. Verify inventory configuration:

ansible-inventory --list
ansible-inventory --graph

These commands display parsed inventory in JSON format or as a hierarchical tree, helping identify configuration errors.

Verifying Ansible Installation

Checking Ansible Version and Configuration

Confirm Ansible installation and configuration:

ansible --version

The output displays ansible-core version, configuration file in use, module search paths, collection locations, Python version, and Jinja2 templating engine version. This information helps troubleshoot compatibility issues.

Display current configuration values:

ansible-config dump

This command lists all configuration parameters and their current values, indicating whether defaults are being used or custom values are active. For configuration troubleshooting, show the configuration file being used:

ansible-config view

Testing Connectivity with Ping Module

Ansible’s ping module tests connectivity and Python availability on managed nodes:

ansible all -m ping

This command pings all hosts in the inventory. Successful output shows:

web1 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

The SUCCESS status confirms SSH connectivity, proper authentication, and functional Python on the managed node. The "changed": false indicates no modifications were made—ping is a read-only operation.

Test specific groups:

ansible webservers -m ping

For individual hosts:

ansible web1 -m ping

Failures indicate connectivity issues, authentication problems, or missing Python on managed nodes. Verbose output aids troubleshooting:

ansible all -m ping -vvv

Multiple -v flags increase verbosity, displaying detailed SSH connection information.

Running Ad-hoc Commands

Ad-hoc commands execute single tasks without playbooks, useful for quick operations and testing:

ansible all -a "uptime"

This executes the uptime command on all hosts, displaying system uptime and load averages. Check disk usage:

ansible webservers -a "df -h"

Install packages using modules:

ansible all -b -m dnf -a "name=vim state=present"

The -b flag enables privilege escalation (become), and the dnf module installs vim. Gather system facts:

ansible web1 -m setup

This displays comprehensive system information that Ansible collects automatically, including network interfaces, memory, CPU, and operating system details.

Testing Ansible with a Simple Playbook

Creating Your First Playbook

Playbooks define automation workflows in YAML format. Create a test playbook:

nano test-playbook.yml

Add the following content:

---
- name: Install and configure nginx
  hosts: webservers
  become: yes
  
  tasks:
    - name: Install nginx package
      dnf:
        name: nginx
        state: present
    
    - name: Start and enable nginx service
      systemd:
        name: nginx
        state: started
        enabled: yes
    
    - name: Allow HTTP through firewall
      firewalld:
        service: http
        permanent: yes
        state: enabled
        immediate: yes

This playbook targets the webservers group, installs nginx, starts the service, and configures the firewall. The become: yes directive enables privilege escalation for tasks requiring root access.

Running the Test Playbook

Execute the playbook:

ansible-playbook test-playbook.yml

Ansible displays execution progress for each task, showing which hosts are affected and whether changes were made. Output includes:

  • PLAY indicates the playbook section being executed
  • TASK shows individual task execution
  • Task results display ok (no changes), changed (modifications made), or failed (errors)
  • PLAY RECAP summarizes results for all hosts

Run the playbook a second time:

ansible-playbook test-playbook.yml

This demonstrates idempotency—Ansible recognizes that the desired state already exists and makes no changes, showing “ok” instead of “changed” for all tasks.

Verifying Playbook Results

Connect to a managed node:

ssh ansible@web1

Verify nginx installation:

systemctl status nginx
nginx -v

The service should be active and running. Check firewall configuration:

sudo firewall-cmd --list-services

HTTP should appear in the enabled services list, confirming successful playbook execution.

Troubleshooting Common Issues

SSH Connection Problems

“Host key verification failed” errors occur when SSH host keys don’t match known_hosts entries. Disable host key checking temporarily in ansible.cfg or remove the offending entry:

ssh-keygen -R managed-node-1

Permission denied errors indicate authentication failures. Verify SSH keys are properly installed:

ssh -v ansible@managed-node-1

Verbose output shows authentication attempts and failures. Ensure the private key has correct permissions (600) and the public key exists in ~/.ssh/authorized_keys on managed nodes.

Timeout errors suggest network connectivity issues. Verify the managed node is reachable:

ping managed-node-1
telnet managed-node-1 22

Check SSH service status on managed nodes and firewall rules permitting port 22 traffic.

Python Compatibility Issues

“python: command not found” errors occur when Python isn’t installed on managed nodes or is located in a non-standard path. Install Python:

sudo dnf install python3 -y

For systems with Python in unusual locations, set the interpreter path in inventory:

[webservers]
web1 ansible_host=192.168.1.101 ansible_python_interpreter=/usr/bin/python3

Alternatively, set it in ansible.cfg:

[defaults]
interpreter_python = /usr/bin/python3

Permission and Privilege Escalation Errors

“sudo: a password is required” errors occur when passwordless sudo isn’t configured. Edit /etc/sudoers on managed nodes using visudo:

sudo visudo

Add the ansible user:

ansible ALL=(ALL) NOPASSWD: ALL

For temporary password-based sudo, use the --ask-become-pass flag:

ansible-playbook test-playbook.yml --ask-become-pass

Inventory and Configuration Problems

YAML parsing errors indicate syntax issues. Validate YAML syntax using online validators or:

ansible-inventory --list

This parses inventory and displays errors if present. “Host not found” errors occur when hosts aren’t defined in inventory or group names are misspelled. Use verbose mode for detailed debugging:

ansible-playbook test-playbook.yml -vvv

Best Practices for Ansible on Rocky Linux 10

Security Best Practices

Protect sensitive data using Ansible Vault. Encrypt variable files:

ansible-vault encrypt vars/secrets.yml

Execute playbooks with encrypted variables:

ansible-playbook playbook.yml --ask-vault-pass

Implement least privilege principles—create dedicated ansible users with limited sudo access rather than using root. Rotate SSH keys regularly and audit authorized_keys files. Set restrictive file permissions on ansible.cfg and inventory files containing sensitive information. Enable audit logging to track Ansible operations for compliance and security monitoring.

Organization and Structure

Organize playbooks using roles for reusability:

ansible-project/
├── ansible.cfg
├── inventory/
│   ├── production
│   └── staging
├── group_vars/
├── host_vars/
├── roles/
│   ├── webserver/
│   └── database/
└── playbooks/

Use version control systems like Git to track changes, enable collaboration, and provide rollback capabilities. Implement meaningful naming conventions for playbooks, roles, and variables. Document automation workflows and maintain README files explaining project structure and usage.

Performance Optimization

Configure parallel execution in ansible.cfg:

[defaults]
forks = 10

This runs tasks on 10 hosts simultaneously. Enable SSH pipelining:

[ssh_connection]
pipelining = True

Pipelining reduces execution time by minimizing SSH operations. Use fact caching to avoid repeated fact gathering:

[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts
fact_caching_timeout = 3600

Smart gathering only collects facts when needed, and caching stores them for reuse within the timeout period.

Congratulations! You have successfully installed Ansible. Thanks for using this tutorial for installing Ansible open source IT automation engine on your Rocky Linux 10 system. For additional help or useful information, we recommend you check the official Ansible website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button