Mastering Infrastructure as Code: How Ansible with Rocky Linux Revolutionizes Cybersecurity Automation + Video

Listen to this Post

Featured Image

Introduction:

Ansible is an open-source automation tool that eliminates repetitive system administration tasks by using agentless architecture and declarative YAML playbooks. When combined with Rocky Linux—a free, enterprise-grade RHEL-compatible distribution—it provides a robust foundation for enforcing security baselines, patching vulnerabilities, and managing configurations across thousands of servers without SSH key sprawl or complex orchestration scripts.

Learning Objectives:

  • Deploy an Ansible control node on Rocky Linux and configure inventory files for multi-environment automation.
  • Write and execute idempotent playbooks that harden Linux/Windows systems against common cyber threats.
  • Implement role-based automation and encrypted secrets management to achieve compliance (CIS, NIST) at scale.

You Should Know

  1. Setting Up the Ansible Control Node on Rocky Linux

Ansible follows a control node → managed nodes architecture. The control node (your Rocky Linux machine) requires only Python and the `ansible` package, while managed nodes need no agent—just SSH (Linux) or WinRM (Windows) access.

Step‑by‑step installation:

 Update system and install EPEL repository
sudo dnf update -y
sudo dnf install epel-release -y

Install Ansible on Rocky Linux 9/10
sudo dnf install ansible -y

Verify installation
ansible --version

Create an inventory file (/etc/ansible/hosts or a project-specific file):

[bash]
web1.example.com ansible_user=rocky
web2.example.com ansible_user=rocky

[bash]
db1.example.com ansible_user=postgres

[bash]
win-srv01 ansible_host=192.168.1.100 ansible_user=Administrator ansible_password=P@ssw0rd ansible_connection=winrm ansible_winrm_server_cert_validation=ignore

Test connectivity using the `ping` module:

ansible all -i inventory.ini -m ping -u rocky --ask-pass

Security note: Avoid storing plaintext passwords in inventory. Use `–ask-pass` initially, then migrate to SSH keys or Ansible Vault.

2. Writing Idempotent Playbooks for Security Hardening

Idempotency ensures that running a playbook multiple times doesn’t change the system beyond the desired state—critical for audit trails and remediation.

Example playbook (harden-ssh.yml): disables root login, enforces key‑based auth, and changes the SSH port.


<ul>
<li>name: Harden SSH configuration on Rocky Linux servers
hosts: webservers
become: yes
vars:
ssh_port: 2222
tasks:</li>
<li>name: Install openssh-server
dnf:
name: openssh-server
state: present</p></li>
<li><p>name: Update sshd_config directives
lineinfile:
path: /etc/ssh/sshd_config
regexp: "^{{ item.param }}"
line: "{{ item.param }} {{ item.value }}"
state: present
loop:</p></li>
<li>{ param: 'PermitRootLogin', value: 'no' }</li>
<li>{ param: 'PasswordAuthentication', value: 'no' }</li>
<li>{ param: 'Port', value: '{{ ssh_port }}' }
notify: restart sshd</li>
</ul>

<p>handlers:
- name: restart sshd
systemd:
name: sshd
state: restarted

Run the playbook:

ansible-playbook -i inventory.ini harden-ssh.yml

Windows equivalent: use `win_lineinfile` and `win_service` modules to disable SMBv1 or enforce Defender policies.

3. Managing Secrets with Ansible Vault

Hardcoded credentials in playbooks are a major security risk. Ansible Vault encrypts variables or entire files using AES‑256.

Create an encrypted variable file (`secrets.yml`):

ansible-vault create secrets.yml
 Inside the editor, add:
db_password: "Sup3rS3cr3t!"
api_key: "abc123xyz"

Use vault‑encrypted variables in a playbook:

- name: Deploy web app with secrets
hosts: app_servers
vars_files:
- secrets.yml
tasks:
- name: Set database password from vault
lineinfile:
path: /var/www/app/.env
line: "DB_PASSWORD={{ db_password }}"

Run the playbook with vault password:

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

For automation in CI/CD, use `–vault-password-file` with a secure vault‑password script.

  1. Automating Windows Servers via WinRM (No SSH Required)

Ansible manages Windows nodes through WinRM over HTTP/HTTPS. Before automation, configure WinRM on Windows targets (recommend using the `ansible.windows` collection).

On the control node (Rocky Linux):

 Install required Python libraries
pip3 install pywinrm

Test WinRM connection
ansible windows_servers -i inventory.ini -m win_ping

Example playbook – enable Windows Defender real‑time protection:


<ul>
<li>name: Harden Windows endpoints
hosts: windows_servers
tasks:</li>
<li>name: Enable real-time protection
win_shell: Set-MpPreference -DisableRealtimeMonitoring $false
args:
executable: powershell.exe</p></li>
<li><p>name: Set PowerShell execution policy to AllSigned
win_powershell:
script: |
Set-ExecutionPolicy AllSigned -Force

> Troubleshooting: Use `ansible_winrm_transport=credssp` for double‑hop authentication scenarios.

  1. Using Ansible Roles and Galaxy for Reproducible Security Baselines

Roles are reusable, self‑contained units of automation (tasks, handlers, templates, defaults). The official `ansible-galaxy` command downloads community‑vetted roles from Ansible Galaxy.

Download a CIS benchmark role for Rocky Linux:

ansible-galaxy role install mindpointgroup.cis_rocky_linux

Create a `site.yml` that applies the role:

- hosts: all
become: yes
roles:
- mindpointgroup.cis_rocky_linux
vars:
cis_rule_1_1_1_1: true  Ensure mounting of cramfs filesystem is disabled
cis_rule_1_1_1_2: true  Ensure mounting of freevxfs is disabled

Build your own role – for example, a role that installs and configures Fail2ban:

ansible-galaxy role init fail2ban_hardening
 Edit tasks/main.yml
 fail2ban_hardening/tasks/main.yml
- name: Install fail2ban
dnf:
name: fail2ban
state: present
- name: Copy local jail configuration
template:
src: jail.local.j2
dest: /etc/fail2ban/jail.local
notify: restart fail2ban
  1. Integrating Ansible into DevSecOps Pipelines (Jenkins / GitLab)

Continuous security automation requires running Ansible playbooks from CI/CD pipelines, often triggering on code commits or vulnerability scans.

Example GitLab CI stage (`.gitlab-ci.yml`):

stages:
- security_scan
- remediate

ansible-remediate:
stage: remediate
before_script:
- dnf install ansible -y
- ansible-galaxy install -r requirements.yml
script:
- ansible-playbook -i inventory/production playbooks/remediate_cves.yml
only:
- main
when: manual  Require approval for production remediation

Use dynamic inventories to fetch hosts from cloud providers (AWS EC2, Azure) or CMDBs:

ansible-inventory -i aws_ec2.yml --graph

For security logging, enable Ansible’s callback plugins to send JSON output to SIEM systems:

 ansible.cfg
[bash]
stdout_callback = json
callbacks_enabled = actionable, timer

7. Scaling Automation with Ansible Performance Optimizations

When managing 1000+ nodes, default settings cause bottlenecks. Optimize by:

  • Pipelining – reduces SSH round trips (pipelining = True in ansible.cfg).
  • Forks – increase parallel execution: forks = 50.
  • Mitogen – a third‑party accelerator (requires pip install mitogen).

Update `ansible.cfg` on the control node (`/etc/ansible/ansible.cfg`):

[bash]
host_key_checking = False
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_cache
fact_caching_timeout = 3600
forks = 50

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

Benchmark execution speed:

time ansible all -i inventory.ini -m setup --tree /tmp/facts/

For Windows hosts, enable `ansible_winrm_connection_pool` and set `ansible_async = 300` for long‑running tasks.

What Undercode Say

  • Key Takeaway 1: Ansible’s agentless, idempotent design makes it a superior choice for security remediation compared to imperative scripts—reducing drift and ensuring consistent compliance.
  • Key Takeaway 2: Combining Rocky Linux’s enterprise stability with Ansible Galaxy’s pre‑built CIS roles allows security teams to deploy hardened baselines in hours, not weeks.
  • Analysis: The growing adoption of “security as code” demands tools that bridge IT ops and infosec. Ansible’s native support for Windows, Linux, network devices, and cloud APIs, plus its integration with Vault and CI/CD, positions it as the lingua franca for automated GRC (Governance, Risk, Compliance). While Terraform excels at provisioning, Ansible remains unmatched for post‑provision configuration and ongoing remediation. Organizations failing to adopt IaC for security will struggle with patching latency and configuration drift, ultimately increasing breach surface area.

Prediction

By 2028, Ansible will become the default interface for security automation across hybrid environments, displacing legacy configuration management databases (CMDBs) and manual runbooks. As AI‑generated playbooks emerge (e.g., LLMs converting natural language policies into YAML), even small security teams will orchestrate real‑time responses to CVEs. However, the rise of “playbook injection” attacks—malicious roles or vault‑poisoning—will force the creation of Ansible‑specific runtime detection and signing mechanisms. Rocky Linux, being community‑driven and free from commercial licensing, will be the preferred control node OS in air‑gapped and government sectors, driving further innovation in offline‑first automation tooling.

▶️ Related Video (84% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: H%C3%A9ctor Joaqu%C3%ADn – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky