976 words
5 minutes
Automating Server Hardening with Chef InSpec and Ansible

Introduction#

Server hardening is a critical aspect of maintaining a secure and compliant IT infrastructure. Manually configuring and verifying security settings across numerous servers is time-consuming, error-prone, and difficult to scale. This article explores how to automate server hardening using two powerful tools: Chef InSpec for compliance testing and Ansible for automated remediation. By combining these technologies, you can ensure consistent security configurations, detect deviations from desired states, and automatically correct them, significantly reducing your organization’s attack surface.

Understanding the Tools#

Before diving into the automation process, let’s briefly introduce the key players:

  • Chef InSpec: InSpec is an open-source framework for automating security and compliance testing. It allows you to define infrastructure requirements as code, which can then be executed against your servers to verify their compliance. InSpec uses a human-readable language, making it easy to understand and maintain your security policies.

  • Ansible: Ansible is an open-source automation engine that simplifies IT tasks such as application deployment, configuration management, and orchestration. It uses a simple, agentless architecture, relying on SSH to communicate with managed nodes. Ansible playbooks define the desired state of your systems, and Ansible ensures that those systems conform to that state.

The Automation Workflow#

The core of this automation solution lies in a cyclical workflow:

  1. Define Security Policies as InSpec Profiles: Translate your organization’s security policies and hardening guidelines into InSpec profiles. These profiles contain a set of controls that define specific security requirements.

  2. Execute InSpec Scans: Run InSpec scans against your servers to assess their compliance with the defined profiles. InSpec reports on which controls pass and fail, providing a clear picture of your security posture.

  3. Analyze InSpec Results: Analyze the InSpec results to identify servers that deviate from the desired security baseline.

  4. Remediate with Ansible: Use Ansible playbooks to automatically remediate any non-compliant configurations. These playbooks should be designed to bring the servers back into compliance with the InSpec profiles.

  5. Re-run InSpec Scans: After remediation, re-run InSpec scans to verify that the Ansible playbooks have successfully corrected the identified issues.

Defining Security Policies with Chef InSpec#

Let’s illustrate this with an example. Suppose you want to ensure that all servers have a strong password policy. You can define this requirement in an InSpec control:

control 'password-policy' do
  impact 1.0
  title 'Verify password policy'
  desc 'Ensures that the password policy meets organizational standards.'

  describe command('grep "^PASS_MAX_DAYS" /etc/login.defs') do
    its('stdout') { should match /PASS_MAX_DAYS\s+90/ }
  end

  describe command('grep "^PASS_MIN_DAYS" /etc/login.defs') do
    its('stdout') { should match /PASS_MIN_DAYS\s+1/ }
  end

  describe command('grep "^PASS_MIN_LEN" /etc/login.defs') do
    its('stdout') { should match /PASS_MIN_LEN\s+12/ }
  end
end

This InSpec control checks the /etc/login.defs file to ensure that the maximum password age is 90 days, the minimum password age is 1 day, and the minimum password length is 12 characters. If any of these checks fail, the control will report a failure.

You can group multiple controls into an InSpec profile, which represents a complete set of security requirements.

Automating Remediation with Ansible#

If the InSpec scan reveals that a server does not meet the password policy requirements, you can use Ansible to automatically correct the configuration. Here’s an example Ansible playbook that updates the /etc/login.defs file:

---
- hosts: all
  become: true
  tasks:
    - name: Set PASS_MAX_DAYS
      lineinfile:
        path: /etc/login.defs
        regexp: '^PASS_MAX_DAYS'
        line: 'PASS_MAX_DAYS   90'

    - name: Set PASS_MIN_DAYS
      lineinfile:
        path: /etc/login.defs
        regexp: '^PASS_MIN_DAYS'
        line: 'PASS_MIN_DAYS   1'

    - name: Set PASS_MIN_LEN
      lineinfile:
        path: /etc/login.defs
        regexp: '^PASS_MIN_LEN'
        line: 'PASS_MIN_LEN   12'

This Ansible playbook uses the lineinfile module to ensure that the specified lines are present in the /etc/login.defs file. If the lines are not present, they will be added. If they are present but have incorrect values, they will be updated. The become: true directive ensures that the playbook is executed with root privileges.

Integrating InSpec and Ansible#

The power of this approach lies in the integration of InSpec and Ansible. You can use InSpec to identify systems that need remediation and then trigger Ansible to automatically correct the configurations. This can be achieved through scripting or orchestration tools like Jenkins or GitLab CI/CD.

A basic example of how to integrate these tools involves running InSpec from the command line and parsing the output to determine if Ansible needs to be invoked. For instance:

inspec exec password_policy.rb --reporter json > inspec_report.json

# Parse the JSON report (using jq for example)
if jq '.results[].status == "failed"' inspec_report.json | grep -q true; then
  echo "Password policy check failed. Running Ansible playbook..."
  ansible-playbook password_policy.yml
else
  echo "Password policy check passed."
fi

This script runs the password_policy.rb InSpec profile, saves the output as inspec_report.json, and then uses jq to check if any controls failed. If any controls failed, the script executes the password_policy.yml Ansible playbook.

Benefits of Automation#

Automating server hardening with Chef InSpec and Ansible offers several benefits:

  • Improved Security Posture: Ensures consistent and enforced security configurations across your infrastructure.
  • Reduced Risk: Minimizes the risk of human error and configuration drift.
  • Increased Efficiency: Automates repetitive tasks, freeing up IT staff to focus on more strategic initiatives.
  • Enhanced Compliance: Provides auditable evidence of compliance with security policies and regulations.
  • Scalability: Easily scales to manage large and complex environments.

Best Practices#

  • Version Control: Store your InSpec profiles and Ansible playbooks in a version control system like Git.
  • Testing: Thoroughly test your InSpec profiles and Ansible playbooks in a non-production environment before deploying them to production.
  • Idempotency: Ensure that your Ansible playbooks are idempotent, meaning that they can be run multiple times without causing unintended side effects.
  • Modularization: Break down your InSpec profiles and Ansible playbooks into smaller, modular components to improve maintainability and reusability.
  • Documentation: Document your InSpec profiles and Ansible playbooks to make them easier to understand and maintain.

Conclusion#

Automating server hardening with Chef InSpec and Ansible is a powerful way to improve your organization’s security posture, reduce risk, and increase efficiency. By defining security policies as code, automating compliance testing, and automatically remediating non-compliant configurations, you can ensure that your servers are consistently hardened and protected against threats. This approach not only strengthens your security defenses but also provides valuable insights into your infrastructure’s compliance status, enabling you to proactively address potential vulnerabilities.

Automating Server Hardening with Chef InSpec and Ansible
https://en.dymripper.com/posts/2025-05-23-automating-server-hardening-with-chef-inspec-and-ansible/
Author
DYMripper
Published at
2025-05-23