Monday, 23 November 2026

Ansible and RHEL

 Interviewer: Tell me about a time you faced a broken Ansible deployment on a Red Hat Enterprise Linux (RHEL) workstation, how you fixed it, and whether it required a full rebuild.

Expert Answer:
Yes, we resolved the broken Ansible environment, and the permanent fix required a clean rebuild of the RHEL workstation rather than patching a corrupted Python dependency tree.
In a recent infrastructure automation project managing 150+ RHEL 8/9 servers, a developer workstation had mixed pip root installations with system dnf packages. This broke ansible-core and SSL modules due to conflicting cryptography and urllib3 versions. Instead of spending hours untangling broken shared libraries, we backed up the playbooks, wiped the workstation, and performed a clean RHEL 9 rebuild using ansible-navigator and Execution Environments (EEs) to permanently isolate dependencies.

Root Cause & Troubleshooting Journey
Before deciding on a rebuild, we ran through a structured diagnostic process:
  1. Initial Symptom: Running ansible-playbook threw an AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms' alongside pkg_resources.DistributionNotFound.
  2. Diagnostic Checks:
    • Checked Python paths (which ansible, head -n 1 $(which ansible)), discovering Ansible was pointing to /usr/local/bin/ansible (installed via sudo pip3) instead of /usr/bin/ansible.
    • Audited installed packages (pip list vs. rpm -qa | grep python3), revealing mismatched versions of pyOpenSSL and cryptography overwriting RHEL’s native RPM-managed Python packages.
  3. Why Rebuild Over Repair: Removing pip packages manually risked breaking dnf and subscription-manager (which rely heavily on RHEL's system Python). A clean rebuild took 30 minutes and guaranteed a supportable, compliant baseline.

Step-by-Step RHEL Workstation Rebuild & Ansible Setup
Phase 1: Pre-Rebuild Backup
Before wiping the machine, we preserved critical automation assets:
  • Backed up local Git repositories, ~/.ansible.cfg, custom inventory files, and SSH keys (~/.ssh/).
  • Exported the list of installed collections (ansible-galaxy collection list > collections_backup.txt).
Phase 2: Clean OS Installation & Registration
  1. Provision RHEL 9: Installed a minimal workstation image via Kickstart/PXE boot to ensure disk encryption (LUKS) and standard partitioning.
  2. Register with Red Hat Subscription Management (RHSM):
    bash
    sudo subscription-manager register --username <user> --password <pass>
    sudo subscription-manager attach --auto
    
    Use code with caution.
  3. Enable Required Repositories: Enabled the official Red Hat Ansible Automation Platform (AAP) or AppStream repositories:
    bash
    sudo subscription-manager repos --enable=rhel-9-for-x86_64-appstream-rpms
    sudo subscription-manager repos --enable=ansible-automation-platform-2.4-for-rhel-9-x86_64-rpms
    
    .
Phase 3: Installing Ansible the "RHEL Way"
Instead of installing legacy monolithic Ansible via pip, we installed ansible-core and container-based tooling:
  1. Install Core Packages via DNF:
    bash
    sudo dnf update -y
    sudo dnf install -y ansible-core ansible-navigator podman git
    
    Verify Installation:
  2. bash
    ansible --version
    # Confirmed Python interpreter points strictly to /usr/bin/python3.9
    
    Use code with caution.
Phase 4: Configuring Execution Environments (EE)
To ensure the workstation never suffered dependency conflicts again, we configured ansible-navigator to run playbooks inside isolated container images:
  1. Authenticate to Red Hat Registry:
    bash
    podman login registry.redhat.io
    
    Use code with caution.
  2. Create ~/.ansible-navigator.yml:
    yaml
    ---
    ansible-navigator:
      execution-environment:
        image: registry.redhat.io/ansible-automation-platform-24/ee-supported-rhel9:latest
        pull:
          policy: missing
      mode: stdout
    
    Use code with caution.
  3. Test Execution:
    bash
    ansible-navigator run site.yml -i inventory/prod
    
    Use code with caution.

Key Challenges Faced During the Project
ChallengeImpactResolution
Root pip Pollutionsudo pip install overwrote /usr/lib/python3.9/site-packages, breaking system tools like dnf.Enforced a strict policy: never use sudo pip. Isolated all Python dependencies inside Python virtual environments (venv) or Execution Environments.
Air-Gapped / Proxy Restrictionsansible-galaxy failed to download collections behind the corporate firewall.Configured HTTP_PROXY / HTTPS_PROXY in /etc/environment and mirrored required collections to an internal Private Automation Hub.
SELinux Context DenialsCustom project directories mounted into Podman containers failed with Permission Denied.Added the :Z volume mount flag in ansible-navigator.yml to automatically relabel container SELinux contexts.

Production Best Practices for Ansible on RHEL
  • Adopt Execution Environments (EEs): Package your Ansible version, collections, and Python libraries into an immutable container image using ansible-builder. What works on your workstation will work identically in CI/CD and Ansible Automation Controller.
  • Never Mix dnf and sudo pip: Keep system Python strictly managed by RPM/DNF. If you must run Ansible locally without containers, use isolated user-space virtual environments (python3 -m venv ~/ansible-venv).
  • Pin Collection Versions: Always maintain a collections/requirements.yml file with exact semantic versions so playbook runs are deterministic across the entire engineering team.
  • Use ansible-lint in Pre-Commit Hooks: Catch syntax errors, deprecated modules, and FQCN (Fully Qualified Collection Name) issues before code is ever pushed to Git.
Q: We recently rebuilt a RHEL control node, and the team is struggling to get Ansible installed and functioning properly with our existing playbooks. How would you diagnose, fix, and standardize this in a RHEL environment, and what challenges do you anticipate?
A:
"In RHEL 8 and 9, the primary reason Ansible fails after a workstation rebuild is a mismatch between the legacy ansible package (Community Ansible) and Red Hat’s supported ansible-core architecture, compounded by missing Python dependencies and unconfigured Red Hat Subscription Management (RHSM) repositories.
To fix this cleanly, I don't rely on pip installs on the system Python, as that breaks RHEL's package management. Instead, I enable the official ansible-core RPM repository via subscription-manager, install ansible-core, and use ansible-galaxy with a requirements.yml file to pull down the exact certified collections our playbooks need—or better yet, standardize the control node using Ansible Execution Environments (EEs) via Podman."

Real-World Project Context (STAR Format)
If you are using this scenario in an interview, frame it using the following project details:
  • Situation: Following a hardware failure and security baseline update, a RHEL 8 control node was rebuilt from scratch. Legacy automation pipelines immediately failed with ModuleNotFoundError and couldn't resolve module/action errors.
  • Task: Restore full automation capabilities for a 150-server hybrid infrastructure within a 4-hour SLA while ensuring the new build adhered to strict enterprise compliance (no unmanaged pip packages).
  • Action: Audited legacy playbooks, enabled official Red Hat ansible-core repositories, decoupled Python dependencies into isolated virtual environments, and migrated collection management to a version-controlled requirements.yml file.
  • Result: Restored deployment pipelines ahead of schedule, reduced control-node configuration drift to zero, and cut future workstation rebuild times from 4 hours to 15 minutes using an automated bootstrap script.

Step-by-Step Resolution in RHEL (RHEL 8 / RHEL 9)
Step 1: Verify Subscription and Enable Repositories
On a freshly rebuilt RHEL workstation, the Ansible repositories are disabled by default.
  1. Check registration status:
    bash
    sudo subscription-manager status
    
    Enable the BaseOS, AppStream, and Ansible repositories. (Note: On RHEL 8.6+ and RHEL 9, ansible-core is included directly in the AppStream repo, whereas older RHEL 8 versions required a separate ansible-2.9 repo).
  2. bash
    # For RHEL 8 / 9 standard AppStream access:
    sudo subscription-manager repos --enable=rhel-9-for-x86_64-appstream-rpms
    

Step 2: Install ansible-core and Essential Tools
Avoid installing Ansible via sudo pip install ansible on RHEL, as it overwrites system Python libraries used by dnf.
bash
sudo dnf install -y ansible-core git python3-pip
Step 3: Restore Ansible Collections
Because ansible-core only ships with basic built-in modules (ansible.builtin), third-party and extended modules (like community.general or ansible.posix) will be missing after a rebuild.
  1. Create or pull your project's requirements.yml:
    yaml
    ---
    collections:
      - name: ansible.posix
        version: 1.5.4
      - name: community.general
        version: 8.1.0
      - name: redhat.rhel_system_roles
    
    Use code with caution.
  2. Install the collections system-wide so all users on the workstation can access them:
    bash
    sudo ansible-galaxy collection install -r requirements.yml -p /usr/share/ansible/collections
    

Step 4: Resolve Python SDK Dependencies Safely
Many Ansible modules (e.g., AWS, VMware, Azure, or Kubernetes modules) require specific Python libraries on the control node. Use a Python Virtual Environment (venv) to keep the OS clean.
bash
# Create a dedicated virtual environment for Ansible
python3 -m venv ~/ansible-venv
source ~/ansible-venv/bin/activate

# Install required Python SDKs (e.g., boto3, pyvmomi, jmespath)
pip install --upgrade pip
pip install boto3 jmespath netaddr
Step 5: Reconfigure ansible.cfg and SSH ControlPersist
A workstation rebuild wipes custom /etc/ansible/ansible.cfg or ~/.ansible.cfg files, causing SSH timeouts or host-key verification failures.
ini
[defaults]
inventory = ./inventory/hosts
collections_path = /usr/share/ansible/collections:~/.ansible/collections
host_key_checking = False
interpreter_python = auto_silent

[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
Key Challenges & How to Overcome Them
ChallengeRoot CauseTechnical Fix
1. couldn't resolve module/action errorsLegacy playbooks used short module names (e.g., ufw or selinux) from Ansible 2.9, which were moved out of ansible-core.Update playbooks to use FQCN (Fully Qualified Collection Names, e.g., ansible.posix.selinux) and install the missing collections via ansible-galaxy.
2. Python Version MismatchRHEL 8 defaults to Python 3.6, while newer ansible-core versions require Python 3.9+ or 3.11.Install python3.11 via dnf and explicitly point ansible_python_interpreter or your venv to /usr/bin/python3.11.
3. Air-Gapped / Restricted NetworkRebuilt workstations in secure environments cannot reach ://ansible.com or PyPI.Use ansible-galaxy collection download on a connected machine to create a .tar.gz bundle, transfer it, and install offline from a local directory.
4. Missing Ansible Vault PasswordsLocal vault password files stored in /home/ were wiped during the OS rebuild.Retrieve the vault key from an enterprise secrets manager (e.g., HashiCorp Vault, CyberArk) and set ANSIBLE_VAULT_PASSWORD_FILE in .bashrc.

Pro-Tip for Senior Interviews: Mention Execution Environments
To stand out as a senior engineer, conclude your answer by explaining how to prevent this problem permanently:
"While fixing the workstation gets us back online, the modern Red Hat best practice is to eliminate local workstation dependencies entirely using Ansible Execution Environments (EEs) via ansible-navigator and Podman. By packaging ansible-core, collections, and Python libraries into an OCI container image, any rebuilt workstation only needs Podman installed to run automation identically every time."

or
Yes, the Ansible package issue on the RHEL workstation rebuild was resolved by aligning the Python interpreter version (ansible-core vs. system Python 3.9/3.11) and enabling the official Red Hat Ansible Automation Platform (AAP) or EPEL repositories so all underlying dependencies matched the RHEL major version.
Below is the complete, detailed breakdown structured as an Expert-Level RHEL & Ansible Interview Guide, covering the project context, prerequisites, step-by-step fix, challenges, troubleshooting, and best practices.

1. Project Context & Scenario
  • Project Goal: Standardize and automate the provisioning and configuration of developer and operations workstations running Red Hat Enterprise Linux (RHEL 8/9) using Ansible.
  • The Issue: After rebuilding a workstation from a minimal RHEL ISO, installing ansible failed with broken Python dependencies (python3-resolvelib, python3-jinja2), missing repository errors, or ansible-playbook crashing due to an unsupported Python runtime mismatch.
  • The Fix: Standardized the base OS repository subscriptions (subscription-manager), enabled the AppStream/AAP repositories, installed ansible-core paired with the supported Python 3.x runtime, and isolated collection dependencies using Ansible Execution Environments / Python virtual environments.

2. Prerequisites & Dependencies
Before installing or running Ansible on a freshly rebuilt RHEL workstation, verify these baseline requirements:
CategoryRequirement / DependencyDetails
OS & SubscriptionActive Red Hat SubscriptionRequired to access RHEL BaseOS, AppStream, and Ansible repositories via subscription-manager.
Python RuntimePython 3.9+ (RHEL 9) or Python 3.8/3.9 (RHEL 8)ansible-core 2.14+ strictly requires Python 3.9 or newer on the control node.
Core Packagesansible-core, python3-pip, sshpass, gitsshpass is required if using password-based SSH authentication instead of SSH keys.
Python Librariesjinja2, PyYAML, cryptography, resolvelibUsually pulled automatically via RPM, or via pip if using virtual environments.
Network & AccessPort 22 (SSH) & HTTPS (443)Outbound 443 to ://redhat.com and ://ansible.com; Port 22 to managed nodes.

3. Step-by-Step Resolution (Workstation Rebuild Fix)
Step 1: Register the System and Verify Repositories
On a fresh RHEL rebuild, repositories are unavailable until the system is attached to Red Hat Subscription Management (RHSM).
bash
sudo subscription-manager register --username <your_rh_user>
sudo subscription-manager refresh
sudo subscription-manager repos --list-enabled
Step 2: Enable Required Repositories
  • For RHEL 9 (Recommended native approach): ansible-core is included directly in the standard AppStream repository.
    bash
    sudo subscription-manager repos --enable=rhel-9-for-x86_64-baseos-rpms \
                                         --enable=rhel-9-for-x86_64-appstream-rpms
    
    .
  • For RHEL 8: Enable the dedicated Ansible Automation Platform repo (or EPEL if using community packages).
    bash
    sudo subscription-manager repos --enable=ansible-automation-platform-2.4-for-rhel-8-x86_64-rpms
    
    Use code with caution.
Step 3: Clean DNF Cache & Remove Conflicting Pip Installs
A common cause of failure during rebuilds is mixing sudo pip install ansible with RPM packages. Remove global pip installations first:
bash
sudo pip3 uninstall -y ansible ansible-core
sudo dnf clean all
sudo rm -rf /var/cache/dnf
Use code with caution.
Step 4: Install ansible-core and Essential Tools
Install the supported RPM package cleanly:
bash
sudo dnf install -y ansible-core git python3-pip sshpass
Use code with caution.
Step 5: Verify Installation & Python Interpreter Mapping
Confirm that Ansible is pointing to the correct Python binary and config file:
bash
ansible --version
Use code with caution.
Expected output check: Ensure python version matches the system Python (/usr/bin/python3.9 or 3.11) and configured module search path is valid.
Step 6: Install Required Ansible Collections
Because ansible-core only ships with built-in modules (ansible.builtin), install community or Red Hat certified collections explicitly:
bash
ansible-galaxy collection install community.general ansible.posix
Use code with caution.

4. Expert Interview Q&A
Q1: Why did dnf install ansible fail on a minimal RHEL 9 build, and why do we install ansible-core instead?
Answer: Starting with RHEL 8.6 and RHEL 9, Red Hat deprecated the monolithic community ansible RPM package from default repositories and replaced it with ansible-core. ansible-core provides the core engine, CLI tools, and minimal built-in modules, while extended modules were decoupled into Ansible Collections (ansible-galaxy). Attempting to install ansible without EPEL fails with "No match for argument: ansible."
Q2: How do you resolve ModuleNotFoundError: No module named 'ansible' after upgrading Python on a RHEL workstation?
Answer: RPM-installed ansible-core is compiled against a specific system Python version (e.g., /usr/bin/python3.9). If an admin updates /usr/bin/python3 via alternatives to Python 3.11, Ansible breaks because its libraries live in /usr/lib/python3.9/site-packages/.
  • Fix: Never overwrite the default system Python symlink on RHEL. Either revert alternatives --config python3 back to the OS default, or install Ansible inside an isolated Python virtual environment (python3.11 -m venv ~/ansible-venv).
Q3: What is the difference between ansible_python_interpreter and the Control Node Python version?
Answer:
  • Control Node Python: Runs the Ansible engine itself on the workstation.
  • ansible_python_interpreter: Inventory variable that tells Ansible which Python binary to execute modules with on the target/managed host (e.g., /usr/libexec/platform-python on RHEL 8).

5. Key Challenges & Troubleshooting Matrix
ChallengeRoot CauseTroubleshooting & Resolution
Dependency Hell (resolvelib conflict)Mixing pip packages as root with dnf RPM packages.Run pip list as root, uninstall conflicting libraries, and strictly use dnf for OS packages or venv for Python packages.
SSL Certificate Verify Failed on ansible-galaxyCorporate proxy/firewall injecting self-signed inspection certificates.Add the corporate root CA to /etc/pki/ca-trust/source/anchors/, run sudo update-ca-trust, or pass --ignore-certs temporarily.
SELinux blocking local file/template tasksMissing libselinux-python bindings when Ansible modifies SELinux-enforced paths on localhost.Install python3-libselinux via dnf so Ansible can properly manage SELinux file contexts.
Slow playbook execution on workstationDefault SSH connection overhead and fact-gathering on every run.Enable SSH multiplexing (ControlMaster=auto) and set gathering = smart with JSON fact caching in ansible.cfg.

6. Production Best Practices
  1. Never Run pip install with sudo: Keep system Python clean for RHEL OS tools (dnf, subscription-manager). Use python3 -m venv or ansible-navigator (containerized Execution Environments) for project-specific Ansible versions.
  2. Pin Collection Versions in requirements.yml: Never rely on latest unpinned collections during workstation rebuilds. Always maintain a requirements.yml file in Git:
    yaml
    collections:
      - name: community.general
        version: 8.1.0
      - name: ansible.posix
        version: 1.5.4
    
    Use code with caution.
  3. Keep ansible.cfg Local to the Project: Avoid editing /etc/ansible/ansible.cfg globally. Place ansible.cfg inside your Git repository root so workstation rebuilds are 100% reproducible upon git clone.
  4. Use SSH Keys + ssh-agent: Avoid storing plaintext passwords or relying on sshpass in production workflows; use Ed25519 SSH keys with ansible-vault for secrets.

Q: The most common cause of a broken Ansible package after a RHEL workstation

The most common cause of a broken Ansible package after a RHEL workstation rebuild is a Python runtime mismatch or missing/unregistered Red Hat subscription repositories. Because RHEL relies heavily on specific system Python versions (platform-python or python3.11/3.12) and distinct repository channels (ansible-automation-platform or rhel-9-for-x86_64-appstream-rpms), rebuilding a host often leaves Ansible pointing to an orphaned virtual environment or lacking the correct ansible-core RPM dependencies.
Below is an expert-level interview question, model answer, and step-by-step troubleshooting guide tailored for a RHEL environment.

Interview Question & Answer
Interviewer: "We recently rebuilt a RHEL control node/workstation, and now Ansible is either missing, throwing ModuleNotFoundError for core libraries, or failing to install via dnf. How do you diagnose the root cause and permanently fix the environment?"
Expert Answer:
"When a RHEL workstation is rebuilt, Ansible failures almost always come down to three things: unattached subscription repositories, Python interpreter collisions (mixing pip installs with system dnf RPMs), or missing collections that previously lived in a user's home directory.
First, I check which ansible and ansible --version to see if it’s executing from /usr/bin/ansible (RPM-managed) or /usr/local/bin / ~/.local/bin (pip-managed). Next, I verify active RHEL repositories using subscription-manager to ensure the AppStream or Ansible Automation Platform (AAP) repos are enabled.
To fix it cleanly and prevent future drift, I purge any broken pip remnants from system paths, register the host, and either install the official ansible-core RPM via dnf or isolate the tooling inside a dedicated Python virtual environment or Ansible Execution Environment (EE) container using podman and ansible-navigator."

Step-by-Step Fix on RHEL (RHEL 8 / RHEL 9)
Step 1: Diagnose the Current State
Run these checks to identify whether you have a path conflict, a broken Python link, or a missing package:
bash
# Check where ansible is located (RPM vs. pip)
which -a ansible

# Check Python version and Ansible module paths
ansible --version

# Check if ansible-core is installed via RPM
rpm -qa | grep -i ansible
  • Red Flag: If which ansible points to /usr/local/bin/ansible or ~/.local/bin/ansible and fails with No module named 'ansible', a system Python upgrade during the rebuild broke a previous pip installation.
Step 2: Clean Up Conflicting pip Installations (If Present)
Avoid mixing sudo pip install ansible with RHEL system packages, as it overwrites system-managed dependencies.
bash
# Remove broken pip-installed ansible packages
sudo pip3 uninstall -y ansible ansible-core
pip3 uninstall -y ansible ansible-core
Step 3: Verify RHEL Subscription & Enable Repositories
After a rebuild, a RHEL workstation must be re-registered to pull ansible-core (which is included in standard RHEL AppStream repos for RHEL 8.6+ and RHEL 9).
bash
# Check subscription status
sudo subscription-manager status

# If unregistered, attach your subscription
sudo subscription-manager register --username <your-rh-user> --auto-attach

# Verify AppStream is enabled (contains ansible-core)
sudo subscription-manager repos --enable=rhel-9-for-x86_64-appstream-rpms
# (For RHEL 8, use: rhel-8-for-x86_64-appstream-rpms)
Step 4: Reinstall Ansible Cleanly
Depending on your organization's standard, choose Option A (standard system RPM) or Option B (isolated virtual environment for custom Python dependencies).
Option A: Standard System Installation via DNF (Recommended for most workstations)
bash
sudo dnf clean all
sudo dnf install -y ansible-core
Option B: Isolated Python Virtual Environment (Recommended if you need specific Ansible versions or third-party SDKs like boto3 or pyvmomi)
bash
# Install Python 3.11+ and pip via DNF
sudo dnf install -y python3.11 python3.11-pip

# Create and activate a dedicated venv
python3.11 -m venv ~/ansible-venv
source ~/ansible-venv/bin/activate

# Upgrade pip and install ansible-core
pip install --upgrade pip
pip install ansible-core
Step 5: Restore Missing Collections & Roles
Rebuilding a workstation wipes ~/.ansible/collections. Reinstall your required collections (e.g., ansible.posix, community.general) using a requirements.yml file:
bash
ansible-galaxy collection install ansible.posix community.general
(Tip: For enterprise RHEL environments, you can also install RPM-packaged collections directly via sudo dnf install rhel-system-roles.)
Step 6: Verify the Fix
Run a quick local ping test to confirm the interpreter, inventory parsing, and module execution all work:
bash
ansible --version
ansible localhost -m ansible.builtin.ping

Q: What is Daily RHEL 8 & 9 System Administration Tasks

1. Daily SysAdmin & Automation Activities (With Commands)
In an enterprise environment, daily tasks split between ad-hoc troubleshooting/verification on RHEL servers and automated state enforcement via Ansible.
A. RHEL 8 & 9 Daily Operations
  • System Health & Performance Triage:
    bash
    uptime && free -h && df -hT                # Load average, memory, and filesystem usage
    systemctl --failed                         # Check for crashed services
    journalctl -p 3 -xb                        # View critical/error logs since last boot
    
    Use code with caution.
  • Package & Security Patching (dnf):
    bash
    dnf check-update --security                # List pending security advisories
    dnf updateinfo list cves                   # View specific CVEs affecting the host
    dnf history list                           # Audit recent package transactions
    
    Use code with caution.
  • Storage & LVM Management:
    bash
    lsblk -f                                   # Check block devices, UUIDs, and mount points
    vgs && lvs                                 # Check Volume Group free space and Logical Volumes
    lvextend -r -L +10G /dev/mapper/rhel-var   # Extend LV and resize XFS/ext4 filesystem online
    
    Use code with caution.
  • SELinux & Firewall Management:
    bash
    getenforce                                 # Verify SELinux is Enforcing
    ausearch -m avc -ts recent                 # Check recent SELinux denials
    firewall-cmd --list-all                    # Verify active firewall zones and open ports
    
    Use code with caution.
B. Ansible Daily Operations
  • Ad-Hoc Fleet Verification:
    bash
    ansible all -m ping -o                                         # Quick connectivity check
    ansible webservers -m shell -a "uptime; df -h /var" -b         # Check disk & uptime across fleet
    ansible dbservers -m setup -a "filter=ansible_distribution*"   # Gather OS version facts
    
    Use code with caution.
  • Playbook Execution & Validation:
    bash
    ansible-playbook site.yml --syntax-check                       # Validate YAML syntax
    ansible-playbook site.yml --check --diff                       # Dry-run with file change diffs
    ansible-playbook patch.yml --limit "prod_web" --forks 10       # Targeted rollout with concurrency
    
    Use code with caution.
  • Secrets Management (ansible-vault):
    bash
    ansible-vault create group_vars/prod/vault.yml                 # Create encrypted variable file
    ansible-vault edit group_vars/prod/vault.yml                   # Edit encrypted secrets securely
    
    Use code with caution.

2. Real-World Project Blueprint: Automated RHEL 8/9 Patching & CIS Hardening
Project Overview
  • Goal: Automate monthly security patching and enforce CIS (Center for Internet Security) Level 1 compliance across 300+ RHEL 8 and RHEL 9 production servers with zero manual intervention and automated rollback protection.
  • Architecture: GitLab (Source Control) → Ansible Automation Platform (AAP) / AWX → RHEL 8/9 Fleet (via Bastion/Jump Host).
Prerequisites & Dependencies
  1. Control Node: RHEL 9 running ansible-core (2.15+), Python 3.9+, ansible-navigator, and git.
  2. Managed Nodes: RHEL 8.x / 9.x with Python 3 installed, SSH port 22 open from the Control Node, and a dedicated service account (ansible_svc) with passwordless sudo privileges.
  3. Collections Required (requirements.yml):
    • ansible.posix (for sysctl, mount, firewalld, selinux)
    • community.general (for lvg, lvol, timezone)
    • redhat.rhel_system_roles (official supported roles for network, timesync, selinux, storage)
  4. Infrastructure Dependencies: Internal Red Hat Satellite or local Yum/DNF mirror repository, valid Red Hat subscriptions, and sufficient free space in /boot (at least 300MB) and Volume Groups for LVM snapshots.
Step-by-Step Execution Workflow
  1. Pre-Flight Checks: Verify disk space (/boot and /var), check cluster/load-balancer health, and validate repository connectivity.
  2. Snapshot / Backup: Trigger VMware snapshots via community.vmware.vmware_guest_snapshot or create local LVM snapshots before modifying OS binaries.
  3. Traffic Drain: Remove target node from HAProxy / F5 Load Balancer pool using a pre_tasks block (serial: 20%).
  4. Patch Execution: Apply security updates using the ansible.builtin.dnf module (security: yes, state: latest).
  5. Reboot & Reconnect: Check if a reboot is required (needs-restarting -r), reboot via ansible.builtin.reboot, and wait for SSH to return.
  6. CIS Compliance & Post-Checks: Apply RHEL System Roles (selinux, timesync, sshd), verify critical services (systemctl is-active), and re-add the node to the load balancer.
Key Project Challenges & Resolutions
  • Challenge: In-place minor version upgrades or kernel patches failing due to a full /boot partition.
    • Resolution: Added a pre-task running package-cleanup --oldkernels --count=2 (or dnf remove --oldinstallonly) and failing the play early if /boot had < 250MB free.
  • Challenge: RHEL 8 uses network-scripts (legacy) or NetworkManager, while RHEL 9 completely drops network-scripts and uses keyfiles (/etc/NetworkManager/system-connections/).
    • Resolution: Standardized all network automation using the official redhat.rhel_system_roles.network role, which abstracts OS version differences automatically.

3. Production Troubleshooting Scenarios
Issue / SymptomRoot CauseDiagnostic & Fix Steps
SSH hangs or times out during Ansible Gathering FactsSlow DNS reverse lookups, hung NFS mounts, or large LVM/multipath scans during setup module execution.1. Run ansible host -m setup -vvv to see where it hangs.
2. Disable unnecessary fact subsets: gather_subset: ['!hardware', '!network'].
3. Set UseDNS no in /etc/ssh/sshd_config.
RHEL 9 service fails to start after moving config files with Ansiblecopy or template module placed a file from /tmp with admin_home_t or tmp_t SELinux context instead of etc_t / httpd_config_t.1. Check ls -Z /path/to/file.
2. Run restorecon -Rv /path/to/file.
3. Add setype: _default in the Ansible copy/template task.
Playbook fails with Failed to set permissions on the temporary files Ansible needs to createBecoming an unprivileged user (e.g., become_user: oracle) from another unprivileged user without ACLs enabled.1. Install acl package on managed nodes (dnf install acl).
2. Or set allow_world_readable_tmpfiles = True in ansible.cfg (less secure, use ACLs instead).
RHEL 9 legacy app fails SSH/TLS connection to older applianceRHEL 9 DEFAULT crypto-policy disables SHA-1, TLS 1.0/1.1, and RSA keys < 2048 bits.1. Verify policy: update-crypto-policies --show.
2. Temporarily allow legacy algorithms if strictly required: update-crypto-policies --set LEGACY (or create a custom subpolicy).

4. Enterprise Best Practices (RHEL 8/9 & Ansible)
  • Use RHEL System Roles: Avoid writing custom shell scripts for configuring chrony, SELinux, firewalld, or kdump. Use redhat.rhel_system_roles to ensure idempotency across RHEL 7, 8, and 9.
  • Enforce Immutable / Idempotent Tasks: Never use shell or command modules if a native module exists. If you must use command, always define creates:, removes:, or changed_when: to preserve idempotency.
  • Optimize ansible.cfg for Scale:
    • Enable SSH Pipelining (pipelining = True) to reduce SSH connections per task from 3 to 1.
    • Enable Fact Caching (Redis or JSON file) so playbooks don't re-gather static hardware facts on every run.
    • Use Strategy free for independent tasks so fast servers don't wait for slow ones.
  • Isolate Execution Environments: Package your Ansible collections, Python libraries, and ansible-core into container images (Execution Environments) using ansible-builder to eliminate dependency conflicts across teams.

5. Expert-Level Interview Questions & Answers
Q1: What are the major architectural differences between RHEL 8 and RHEL 9 that impact automation and administration?
Answer:
  1. Network Configuration: RHEL 9 completely removes legacy ifcfg scripts (/etc/sysconfig/network-scripts/) and defaults to NetworkManager keyfiles (/etc/NetworkManager/system-connections/).
  2. Cryptography: RHEL 9 enforces stricter DEFAULT crypto-policies, completely deprecating SHA-1 signatures, which often breaks older SSH keys and third-party RPM GPG keys.
  3. SSH Root Login: RHEL 9 disables password-based root SSH login by default (PermitRootLogin prohibit-password).
  4. Cgroups: RHEL 9 defaults to cgroups v2 (RHEL 8 used v1 by default), impacting container runtimes (Podman) and resource limits (systemd slices).
Q2: How do you handle zero-downtime rolling updates in Ansible if a server fails mid-playbook?
Answer: Use the serial keyword (e.g., serial: "25%" or serial: [1, 5, "25%"] for canary deployments) combined with max_fail_percentage: 10. If more than 10% of the current batch fails, Ansible halts the entire playbook immediately before touching the remaining healthy batches. Pair this with block / rescue / always sections to automatically roll back changes or keep failed nodes out of the load balancer.
Q3: Explain the difference between import_tasks and include_tasks in Ansible.
Answer:
  • import_tasks (Static): Pre-processed when the playbook is parsed before execution begins. Variables inside the file name cannot be dynamic per-host, and tags applied to the import apply to all tasks inside it.
  • include_tasks (Dynamic): Processed at runtime when Ansible reaches that step. It supports loops (loop:), dynamic filenames based on host facts (e.g., include_tasks: "{{ ansible_os_family }}.yml"), and conditional execution per host.
Q4: How do you troubleshoot an SELinux denial without disabling SELinux?
Answer:
  1. Keep SELinux in Enforcing mode (getenforce).
  2. Search the audit log for AVC denials: ausearch -m avc -ts recent or run sealert -a /var/log/audit/audit.log.
  3. Identify whether it is a file context issue (fix with semanage fcontext -a -t <type> "/path(/.*)?" followed by restorecon -Rv /path), a port label issue (fix with semanage port -a -t <type> -p tcp <port>), or a boolean toggle (setsebool -P <boolean_name> on).
Q5: Where does set_fact sit in Ansible's variable precedence hierarchy, and why does it matter?
Answer: set_fact sits near the very top of Ansible's 22 levels of variable precedence (level 19—higher than inventory variables, group_vars, host_vars, and playbook vars, overridden only by include_vars, role/block params, and -e extra vars). Because of this, once a variable is defined via set_fact, it persists in host memory for the rest of the play and cannot be accidentally overwritten by lower-precedence role defaults or group variables.
or
1. Daily RHEL 8 & 9 System Administration Tasks
System Health & Performance Monitoring
Check system uptime, load averages, memory usage, and disk space before starting maintenance.
bash
# Check uptime and load average
uptime

# Monitor real-time CPU and memory usage (press 'q' to exit)
top

# Check free and used memory in human-readable format
free -h

# Check disk space usage across mounted filesystems
df -h

# Identify large directories in /var (common culprit for full disks)
du -sh /var/* | sort -hr | head -n 10
Use code with caution.
Service & Log Management
Verify that critical services are running and scan for recent errors.
bash
# List all failed systemd services
systemctl --failed

# Check status, restart, or reload a specific service (e.g., sshd, httpd, nginx)
systemctl status <service_name>
sudo systemctl restart <service_name>

# View recent system logs with errors (priority 3) from today
journalctl -p 3 -S today

# Follow live logs for a specific service
journalctl -u <service_name> -f
Use code with caution.
Patch & Package Management (dnf)
RHEL 8 and 9 use dnf as the default package manager.
bash
# Check for available updates
sudo dnf check-update

# Apply only security-related updates
sudo dnf update --security -y

# View recent package installation/update history
sudo dnf history list
Use code with caution.
Network & Security Checks
Verify active network interfaces, open ports, and SELinux/Firewall states.
bash
# View IP addresses and network interfaces
ip -br a

# List listening TCP/UDP ports and associated processes
ss -tulnp

# Check active firewall rules
sudo firewall-cmd --list-all

# Verify SELinux status (should typically be Enforcing)
getenforce
Use code with caution.

2. Daily Ansible Automation Tasks
Inventory & Connectivity Verification
Ensure your control node can communicate with managed hosts before running playbooks.
bash
# Ping all hosts in the default or specified inventory
ansible all -m ping -i inventory.ini

# Gather basic OS facts (like RHEL version) across hosts
ansible all -m setup -a "filter=ansible_distribution*" -i inventory.ini
Use code with caution.
Ad-Hoc Commands for Quick Checks
Run one-off commands across multiple RHEL servers without writing a full playbook.
bash
# Check disk space across all web servers
ansible webservers -a "df -h /" -i inventory.ini

# Restart a service across a group of servers using privilege escalation (-b)
ansible webservers -m service -a "name=httpd state=restarted" -b -i inventory.ini

# Check if a specific security patch/package is installed
ansible all -m shell -a "rpm -qa | grep openssl" -i inventory.ini
Use code with caution.
Playbook Execution & Validation
Run syntax checks and dry runs before applying changes to production environments.
bash
# Validate playbook syntax
ansible-playbook site.yml --syntax-check

# Perform a "Dry Run" (Check mode) to see what changes would occur without applying them
ansible-playbook site.yml -i inventory.ini --check --diff

# Execute a playbook targeting a specific host group
ansible-playbook site.yml -i inventory.ini --limit dbservers

# Run a playbook that requires an Ansible Vault password for encrypted secrets
ansible-playbook deploy.yml -i inventory.ini --ask-vault-pass
Use code with caution.


1. Daily Activities & Essential Commands (RHEL 8/9 & Ansible)
RHEL 8 & 9 Daily System Administration
  • System Health & Performance:
    • Check boot time and slow services: systemd-analyze blame
    • Monitor real-time CPU, memory, and disk I/O: top, htop, vmstat 1 5, iostat -xz 1
    • Inspect kernel and service logs: journalctl -u sshd --since "1 hour ago" -p err
  • Storage & LVM Management:
    • Scan and list block devices: lsblk -f, blkid
    • Extend an XFS filesystem online:
      bash
      lvextend -r -L +10G /dev/mapper/rhel-var
      
      Use code with caution.
      (Note: -r automatically runs xfs_growfs on XFS).
  • Package & Module Management (dnf):
    • List and switch Application Streams (RHEL 8/9): dnf module list php, dnf module enable php:8.2
    • Apply security updates only: dnf update --security -y
    • Check transaction history and rollback: dnf history, dnf history undo <ID>
  • Networking & Security (SELinux & Firewalld):
    • Configure static IP via nmcli:
      bash
      nmcli con mod eth0 ipv4.addresses 10.0.1.50/24 ipv4.gateway 10.0.1.1 ipv4.method manual && nmcli con up eth0
      
      Use code with caution.
    • Manage SELinux contexts & booleans: semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?", restorecon -Rv /web, setsebool -P httpd_can_network_connect on
    • Manage firewall rules: firewall-cmd --permanent --add-service=https && firewall-cmd --reload
Ansible Daily Operations
  • Ad-Hoc Diagnostics:
    • Ping and check disk space across fleet: ansible webservers -m shell -a "df -h /var"
    • Gather specific hardware facts: ansible db01 -m setup -a "filter=ansible_memtotal_mb"
  • Playbook Execution & Safety:
    • Syntax check and dry-run with diffs: ansible-playbook site.yml --syntax-check && ansible-playbook site.yml --check --diff
    • Limit execution to specific hosts/tags: ansible-playbook site.yml --limit "web01,web02" --tags "nginx,ssl"
    • Manage encrypted secrets: ansible-vault edit group_vars/prod/vault.yml

2. Enterprise Project Architecture (Interview Showcase)
Project Title: Automated Zero-Touch OS Patching & CIS Level 1 Compliance Remediation for 400+ RHEL 8/9 Servers
Prerequisites & Dependencies
  • Control Node: RHEL 9 server running ansible-core 2.15+, Python 3.11, sshpass, git, and Ansible Automation Platform (AAP) / AWX.
  • Managed Nodes: RHEL 8.8+ / 9.2+ with Python 3.9+, passwordless SSH via dedicated service account (svc_ansible), sudo privileges (NOPASSWD), and access to Red Hat Satellite / local YUM mirrors.
  • Collections: ansible.posix, community.general, redhat.rhel_system_roles.
Detailed Implementation Steps
  1. Dynamic Inventory: Integrated AWX with VMware vCenter / AWS EC2 plugins to dynamically group servers by OS version (rhel8, rhel9) and environment (dev, qa, prod).
  2. Pre-Patch Validation Role: Checked /boot and /var free space (>2GB), verified pacemaker/cluster health, and triggered automated VM snapshots via API.
  3. Rolling Execution (serial): Patched production clusters in batches (serial: "20%") with max_fail_percentage: 5 to halt immediately if an anomaly occurred.
  4. Patching & Reboot: Executed ansible.builtin.dnf with security: true, checked needs-restarting -r, and performed controlled reboots via ansible.builtin.reboot.
  5. Post-Patch & CIS Hardening: Applied rhel-system-roles.timesync and sshd hardening roles, validated application HTTP endpoints via uri module, and generated an HTML compliance report emailed to stakeholders.
Key Challenges Faced
  • Inconsistent Python Interpreters: RHEL 8 uses Python 3.6/3.8 while RHEL 9 defaults to Python 3.9+, causing module execution mismatches.
  • Full /boot Partitions: Older RHEL 8 builds had 500MB /boot partitions that failed when installing new kernels.
  • Application Freeze During Patching: Database and middleware teams required custom pre-stop and post-start hooks without manual intervention.

3. Expert Interview Questions & Answers
Q1: How do you handle Python interpreter differences across mixed RHEL 8 and RHEL 9 environments in Ansible?
  • Answer: Set interpreter_python = auto_silent in ansible.cfg. Ansible automatically discovers /usr/bin/python3 (or /usr/libexec/platform-python on RHEL 8) without throwing discovery warnings. For custom virtual environments on specific hosts, override ansible_python_interpreter in host_vars.
Q2: Explain a critical difference between RHEL 8 and RHEL 9 regarding SSH and crypto policies that impacts Ansible.
  • Answer: RHEL 9 enforces the DEFAULT system-wide crypto policy that disables SHA-1 signatures and older RSA keys (ssh-rsa). Older Ansible control nodes or legacy SSH keys fail with no mutual signature algorithm. To fix this properly, migrate control node keys to Ed25519 (ssh-keygen -t ed25519) rather than downgrading RHEL 9's crypto policy to LEGACY.
Q3: Your Ansible playbook hangs indefinitely on a specific task across 50 servers. How do you troubleshoot and prevent this?
  • Answer:
    1. Run with -vvvv and set ANSIBLE_DEBUG=1 to see the exact SSH command hanging (often a sudo password prompt or an interactive dnf prompt).
    2. Check on the target node using ps auxf | grep python to see if a child process (like an NFS mount hang or rpm lock) is stuck in D (uninterruptible sleep) state.
    3. Prevention: Configure timeout = 30 in ansible.cfg and use async: 300 with poll: 10 for long-running tasks.
Q4: How do you safely manage sensitive variables (passwords, API keys) in Ansible Git repositories?
  • Answer: Use Ansible Vault with Vault IDs (--vault-id prod@prompt) to separate dev and prod secrets. Store variables in group_vars/all/vault.yml with a vault_ prefix, and reference them in vars.yml (e.g., db_pass: "{{ vault_db_pass }}") so developers can grep variable names without decrypting the vault. In CI/CD or AAP, inject the vault password via HashiCorp Vault or CyberArk credentials.
Q5: How do you troubleshoot an SELinux denial without disabling SELinux?
  • Answer: Never run setenforce 0 in production. Instead:
    1. Check /var/log/audit/audit.log or run ausearch -m AVC,USER_AVC -ts recent.
    2. Pipe the denial into audit2why to understand if a boolean or file context fix is needed (e.g., semanage fcontext + restorecon).
    3. Only if no boolean exists for a custom third-party app, generate a custom policy module using audit2allow -M custom_app and load it with semodule -i custom_app.pp.

4. Troubleshooting Matrix (RHEL & Ansible)
Issue / SymptomRoot CauseResolution
Error: Failed to download metadata for repoExpired RHSM certificate or proxy block on RHEL 8/9.Run subscription-manager refresh, dnf clean all, and verify /etc/rhsm/rhsm.conf proxy settings.
UNREACHABLE! Failed to connect to the host via sshMaxStartups limit hit on bastion/jump host when forks=50.Increase MaxStartups 100:30:200 in /etc/ssh/sshd_config or enable SSH ControlPersist in ansible.cfg.
Could not get lock /var/run/yum.pid / RPM DB lockedUnattended dnf-makecache.timer running during playbook execution.Use lock_timeout: 300 in the ansible.builtin.dnf module so Ansible waits gracefully for the lock to release.
System boots into Emergency Mode after fstab editTypo in UUID or missing _netdev option on iSCSI/NFS mounts.Enter root password in emergency shell, run mount -o remount,rw /, fix /etc/fstab, and run mount -a before rebooting.

5. Production Best Practices
  • Ansible Performance Tuning (ansible.cfg):
    • Enable pipelining = True (reduces SSH operations per task from 3 to 1; requires disabling requiretty in /etc/sudoers).
    • Set gathering = smart and configure Redis/JSON fact_caching to avoid re-gathering facts on every run.
  • Idempotency & Code Quality:
    • Avoid shell and command modules unless no native module exists; always pair them with creates, removes, or changed_when.
    • Enforce standards using ansible-lint and test roles locally with Molecule + Podman/containers before merging to main.
  • RHEL 8/9 Hardening:
    • Use tuned-adm profile throughput-performance (or virtual-guest for VMs) for optimal kernel parameters.
    • Configure systemd service drop-in overrides (systemctl edit <service>) instead of editing vendor unit files in /usr/lib/systemd/system/.

6. Production Bash Script: Pre-Patch Health Check & Cleanup
This script is commonly triggered via Ansible (script module) or cron prior to monthly RHEL patching to prevent /boot space failures and verify cluster readiness:
bash
#!/usr/bin/env bash
# Description: RHEL 8/9 Pre-Patch Health Check & Old Kernel Cleanup
# Exit on error, undefined variable, or pipe failure
set -euo pipefail

LOG_FILE="/var/log/pre_patch_audit.log"
MIN_VAR_FREE_MB=2048
MIN_BOOT_FREE_MB=300

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "Starting pre-patch validation on $(hostname -f) ($(cat /etc/redhat-release))"

# 1. Verify Root Execution
if [[ $EUID -ne 0 ]]; then
   log "ERROR: Script must be run as root."
   exit 1
fi

# 2. Check for Failed Systemd Units
FAILED_UNITS=$(systemctl --failed --no-legend | awk '{print $1}')
if [[ -n "$FAILED_UNITS" ]]; then
    log "WARNING: Failed systemd units detected: $FAILED_UNITS"
else
    log "OK: All systemd units are healthy."
fi

# 3. Clean Old Kernels (Keep current + 1 previous) to free /boot
log "Pruning old kernels via dnf..."
dnf remove --oldinstallonly --setopt installonly_limit=2 -y >> "$LOG_FILE" 2>&1 || true

# 4. Validate Disk Space on /boot and /var
BOOT_FREE=$(df -m /boot | awk 'NR==2 {print $4}')
VAR_FREE=$(df -m /var | awk 'NR==2 {print $4}')

if (( BOOT_FREE < MIN_BOOT_FREE_MB )); then
    log "CRITICAL: /boot free space (${BOOT_FREE}MB) is below threshold (${MIN_BOOT_FREE_MB}MB)."
    exit 2
fi

if (( VAR_FREE < MIN_VAR_FREE_MB )); then
    log "CRITICAL: /var free space (${VAR_FREE}MB) is below threshold (${MIN_VAR_FREE_MB}MB)."
    exit 3
fi

# 5. Check Repository Connectivity
if ! dnf check-update --security -q > /dev/null 2>&1; then
    RC=$?
    # Exit code 100 means updates are available (healthy); 1 means repo error
    if [[ $RC -ne 100 ]]; then
        log "CRITICAL: DNF repository metadata check failed with code $RC."
        exit 4
    fi
fi

log "SUCCESS: Pre-patch checks passed (/boot: ${BOOT_FREE}MB free, /var: ${VAR_FREE}MB free)."
exit 0


Quick Comparison: RHEL 8 vs. RHEL 9 Daily Differences
While daily commands are largely identical, keep these operational differences in mind:
Feature / TaskRHEL 8RHEL 9
Default PythonPython 3.6 (Platform Python)Python 3.9
SSH Root LoginAllowed by default (if configured)Disabled by default (PermitRootLogin prohibit-password)
Network Configifcfg scripts & keyfile formatkeyfile format default (/etc/NetworkManager/system-connections/)
Firewall Backendnftables (via firewalld)nftables (via firewalld)
Cgroups Versioncgroups v1 (v2 optional)cgroups v2 by default