Skip to main content

Compliance testing with Ansible and InSpec integration

Project description

ansible-inspec

PyPI - Version PyPI - Downloads Python Version Helm Chart Artifact Hub GitHub Container Registry License


A compliance and infrastructure testing tool that converts InSpec profiles to native Ansible collections, enabling compliance testing through pure Ansible without requiring InSpec on target systems.

Overview

ansible-inspec bridges two powerful open-source projects:

  • Ansible: IT automation platform for configuration management
  • InSpec: Compliance testing framework (used for conversion only)

Why Ansible-InSpec?

๐ŸŽฏ The Perfect Bridge

Ansible-InSpec provides true InSpec-to-Ansible migration, giving you:

๐Ÿ” Enterprise Security

  • ๐Ÿ”‘ Azure AD OAuth2: Enterprise SSO with role-based access control
  • ๐Ÿ”’ Encrypted Credentials: Fernet symmetric encryption for VCS credentials
  • ๐Ÿ‘ฅ Multi-User Support: User authentication and authorization with local accounts
  • ๐Ÿ“Š Audit Logging: Track who performed what actions
  • ๐Ÿ” Session Persistence: 7-day token expiry with automatic session restoration
  • ๐Ÿช Secure Cookies: HTTP-only cookies with configurable security settings

๐Ÿ’พ Production-Ready Storage

  • ๐Ÿ—„๏ธ PostgreSQL Database: Scalable database backend with connection pooling
  • ๐Ÿ”„ Hybrid Storage: Dual-write validation mode for safe migration
  • ๐Ÿ“ˆ Monitoring: Prometheus metrics for storage operations
  • ๐Ÿ” Automatic Cutover: Validated transition from file to database storage

๐Ÿ”„ Version Control Integration

  • ๐Ÿ“ฆ Git Repository Sync: Automatic sync of InSpec profiles from GitHub/GitLab
  • โฑ๏ธ Polling & Webhooks: Both periodic polling and event-driven sync
  • ๐Ÿ” Secure Credentials: Encrypted SSH keys and tokens
  • ๐Ÿš€ Auto-Import: Automatically create job templates from synced profiles

๐ŸŒ Web UI & REST API (v0.3.0)

  • ๐Ÿ“Š Streamlit Dashboard: Modern web interface for job management
  • ๐Ÿ”Œ FastAPI Server: RESTful API for automation and integration
  • ๐Ÿ“‹ Job Templates: Reusable compliance check configurations
  • ๐Ÿš€ Background Execution: Non-blocking job execution with status tracking
  • ๐Ÿ”„ Workflow Management: Chain multiple compliance checks together
  • ๐Ÿ“š Auto-generated API Docs: Swagger UI and ReDoc documentation

โœ… No InSpec Dependency (v0.2.0)

  • Native Translation: Converts InSpec resources to Ansible modules
  • No Target Installation: InSpec NOT required on target systems
  • Only PowerShell: Windows targets need only built-in PowerShell
  • True Migration: Actually migrate FROM InSpec TO Ansible ecosystem

๐Ÿš€ Supported Resource Translation

v0.2.0+ translates these InSpec resources to native Ansible:

  • security_policy โ†’ ansible.windows.win_security_policy
  • registry_key โ†’ ansible.windows.win_reg_stat
  • audit_policy โ†’ ansible.windows.win_shell (auditpol)
  • service โ†’ ansible.windows.win_service_info
  • windows_feature โ†’ ansible.windows.win_feature
  • file โ†’ ansible.windows.win_stat / ansible.builtin.stat

More resources coming in future releases!

โœ… Unified Workflow

  • Single Tool, Two Powers: Combine Ansible's automation with InSpec's compliance DSL
  • Same Inventory: Use your existing Ansible inventory for compliance testing
  • Consistent Access: Leverage Ansible's SSH/WinRM/Docker connections
  • No Duplicate Configuration: Manage infrastructure and compliance from one place

๐Ÿš€ Accelerated Compliance

  • Parallel Testing: Run compliance checks across hundreds of hosts simultaneously
  • Fast Feedback: Get immediate compliance results after infrastructure changes
  • Continuous Compliance: Integrate into CI/CD pipelines for automated validation
  • Shift-Left Security: Test compliance before production deployment

๐Ÿ”’ Enhanced Security & Governance

  • CIS Benchmarks: Convert CIS benchmark profiles to Ansible
  • Custom Policies: Define organization-specific compliance requirements
  • Audit Ready: Generate compliance reports for auditors and stakeholders
  • Drift Detection: Identify configuration drift from security baselines

๐Ÿ’ก Developer Friendly

  • Readable DSL: InSpec's human-readable language for compliance
  • Version Control: Store compliance tests alongside infrastructure code
  • Test-Driven Infrastructure: Build infrastructure with compliance tests first
  • Reusable Profiles: Share compliance tests across teams and projects

๐ŸŒ Multi-Platform Excellence

  • Windows: Windows Server and Desktop (native module support)
  • Linux: All major distributions (Ubuntu, RHEL, CentOS, Debian, etc.)
  • Containers: Docker and Kubernetes
  • Cloud: AWS, Azure, GCP resources (coming soon)

๐Ÿ“Š Comprehensive Reporting

  • Multiple Formats: JSON, HTML, JUnit, CLI output
  • Detailed Results: See exactly what passed/failed and why
  • Trend Analysis: Track compliance over time
  • Integration Ready: Feed results into your monitoring/reporting systems

๐Ÿ’ฐ Cost Effective

  • Open Source: Free, GPL-3.0 licensed
  • No Agent Required: Agentless compliance testing
  • Reduced Dependencies: No InSpec installation on targets (v0.2.0+)
  • Lower Training: Leverage existing Ansible knowledge

๐Ÿ†š Compared to Alternatives

Feature Ansible-InSpec v0.2.0 Pure InSpec Pure Ansible Other Tools
Target Dependency โœ… None (PowerShell only) โŒ InSpec + Ruby โœ… None โš ๏ธ Varies
Native Conversion โœ… Yes โŒ N/A โš ๏ธ Manual โŒ No
Ansible Inventory โœ… Native โŒ Manual โœ… Native โŒ Separate
Compliance DSL โœ… InSpec โœ… InSpec โš ๏ธ Tasks โš ๏ธ Varies
Multi-Platform โœ… Excellent โœ… Excellent โœ… Good โš ๏ธ Limited
Parallel Execution โœ… Yes โš ๏ธ Limited โœ… Yes โš ๏ธ Varies
InSpec Migration โœ… True Migration โŒ N/A โŒ Manual Rewrite โŒ No
Open Source โœ… Yes โœ… Yes โœ… Yes โš ๏ธ Varies

Features

๐ŸŒ Server Features

  • ๐Ÿ” Enterprise Security

    • Azure AD OAuth2 authentication with SSO
    • Local user authentication with secure password hashing
    • 7-day session persistence with automatic token restoration
    • Role-based access control (RBAC)
    • Fernet encrypted credential storage
    • Multi-user support with audit logging
    • HTTP-only cookies with configurable security settings
  • ๐Ÿ’พ Production Database

    • PostgreSQL backend with connection pooling
    • Prisma ORM for type-safe database operations
    • Hybrid storage mode for safe migration
    • Prometheus metrics for monitoring
  • ๐Ÿ”„ VCS Integration

    • Automatic Git repository sync (GitHub/GitLab)
    • Polling and webhook support
    • Encrypted SSH keys and tokens
    • Auto-import of InSpec profiles
  • ๐Ÿ“Š Web UI & REST API

    • Modern FastAPI server with async operations
    • Auto-generated API documentation (Swagger/ReDoc)
    • Job templates for reusable compliance checks
    • Background job execution with real-time status
    • Workflow orchestration for complex scenarios
    • Health checks and Prometheus metrics

๐Ÿ”ง CLI Features

  • Profile Conversion: Convert Ruby-based InSpec profiles to Ansible collections with full custom resource support
  • Chef Supermarket Integration: Access 100+ pre-built compliance profiles from Chef Supermarket (CIS benchmarks, DevSec baselines, DISA STIGs)
  • Infrastructure as Code Testing: Test your infrastructure configurations using InSpec's DSL
  • Ansible Integration: Leverage Ansible's inventory and connection mechanisms
  • Compliance Validation: Validate security and compliance requirements across your infrastructure
  • Multi-Platform Support: Test Linux, Windows, macOS, and cloud platforms
  • Human-Readable Tests: Write tests in a clear, understandable language
  • Multi-Format Reporting: Generate compliance reports in JSON, HTML, JUnit formats
  • InSpec-Free Mode: Run converted profiles without InSpec installation

Architecture

Server Request Flow

sequenceDiagram
    participant Client
    participant API as FastAPI Server
    participant Storage as Storage Backend
    participant DB as PostgreSQL (optional)
    participant Executor as Job Executor
    participant InSpec

    Client->>API: POST /api/v1/job-templates
    API->>Storage: Save template
    alt Database Mode
        Storage->>DB: INSERT job_template
        DB-->>Storage: Success
    else File Mode
        Storage->>Storage: Write JSON to /data
    end
    Storage-->>API: Template created
    API-->>Client: 201 Created

    Client->>API: POST /job-templates/{id}/launch
    API->>Executor: Start background job
    Executor->>InSpec: Execute profile
    InSpec-->>Executor: Results
    Executor->>Storage: Save results
    Storage-->>Executor: Saved
    API-->>Client: Job launched

    Client->>API: GET /jobs/{id}
    API->>Storage: Fetch job
    Storage-->>API: Job data
    API-->>Client: 200 OK with results

Storage Modes

graph LR
    A[Start Server] --> B{DATABASE__URL<br/>configured?}
    B -->|No| C[File Storage]
    B -->|Yes| D[Database Storage]
    C --> E[Local /data directory]
    D --> F[PostgreSQL + Prisma]
    E --> G[Single User Mode]
    F --> H[Multi-User + Auth + VCS]

Quick Start

Installation

# Install with server features (recommended for production)
pip install ansible-inspec

# Or install CLI-only mode
pip install ansible-inspec --no-deps

# Or from source with all features
git clone https://github.com/Htunn/ansible-inspec.git
cd ansible-inspec
pip install -e ".[server]"  # With server dependencies
# OR
pip install -e .             # CLI only

Kubernetes Installation with Helm

Deploy ansible-inspec on Kubernetes using our official Helm chart:

# Add Helm repository
helm repo add ansible-inspec https://htunn.github.io/ansible-inspec/helm
helm repo update

# Install with default settings (includes PostgreSQL)
helm install my-release ansible-inspec/ansible-inspec

# Or customize your installation
helm install my-release ansible-inspec/ansible-inspec \
  --set postgresql.auth.password=yourpassword \
  --set secrets.adminPassword=SecureAdminPass123 \
  --set secrets.adminEmail=admin@yourdomain.com \
  --set replicaCount=3 \
  --set autoscaling.enabled=true \
  --set ingress.enabled=true \
  --set ingress.hosts[0].host=ansible-inspec.yourdomain.com \
  --set streamlit.enabled=true

Production Deployment Example:

# Create custom values file
cat > my-values.yaml <<EOF
# Image configuration
image:
  repository: ghcr.io/htunn/ansible-inspec
  tag: "0.2.11"  # Use specific version in production

# Ingress with TLS
ingress:
  enabled: true
  className: nginx
  annotations:
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
  hosts:
    - host: ansible-inspec.yourdomain.com
      paths:
        - path: /
          pathType: Prefix
  tls:
    - secretName: ansible-inspec-tls
      hosts:
        - ansible-inspec.yourdomain.com

# Authentication
config:
  auth:
    enabled: true
    oauthRedirectUri: "https://ansible-inspec.yourdomain.com/api/v1/auth/callback"
    streamlitUiUrl: "https://ansible-inspec.yourdomain.com"
    azureTenantId: "your-tenant-id"
    azureClientId: "your-client-id"

# Secrets (use external secret management in production)
secrets:
  # Admin user credentials for local password authentication
  adminUsername: "admin"
  adminPassword: "ChangeThisSecurePassword123!"  # REQUIRED for password login
  adminEmail: "admin@yourdomain.com"
  adminName: "Administrator"
  
  # Azure AD OAuth2 (optional, for enterprise SSO)
  azureClientSecret: "your-client-secret"
  
  # Database and encryption
  postgresPassword: "secure-password"
  jwtSecret: "change-this-to-a-secure-random-string"
  encryptionKey: "change-this-to-a-32-byte-base64-encoded-key"

# Enable separate Streamlit UI deployment
streamlit:
  enabled: true
  replicaCount: 1

# PostgreSQL configuration
postgresql:
  enabled: true
  auth:
    password: "secure-password"
  primary:
    persistence:
      size: 20Gi
EOF

# Install with custom values
helm install ansible-inspec ansible-inspec/ansible-inspec \
  -f my-values.yaml \
  -n ansible-inspec \
  --create-namespace

# Check deployment status
kubectl get pods,svc,ingress -n ansible-inspec

# Expected output:
# pod/ansible-inspec-xxxxx          1/1     Running   0          5m
# pod/ansible-inspec-ui-xxxxx       1/1     Running   0          5m
# pod/ansible-inspec-postgresql-0   1/1     Running   0          5m
#
# service/ansible-inspec            ClusterIP   10.x.x.x    <none>   8080/TCP
# service/ansible-inspec-ui         ClusterIP   10.x.x.x    <none>   8501/TCP
# service/ansible-inspec-postgresql ClusterIP   10.x.x.x    <none>   5432/TCP

# Access your deployment
echo "API Documentation: https://ansible-inspec.yourdomain.com/docs"
echo "Streamlit UI: https://ansible-inspec.yourdomain.com/ui"
echo "Health Check: https://ansible-inspec.yourdomain.com/health"

Architecture:

  • API Server (FastAPI): Handles REST API requests, Swagger/ReDoc documentation
  • Streamlit UI: Separate deployment for web interface, accessible at /ui path
  • PostgreSQL: Managed database with persistent storage
  • Ingress: Path-based routing with TLS termination

Features:

  • ๐Ÿ” Production-ready with PostgreSQL database
  • ๐ŸŽจ Separate API and UI deployments for independent scaling
  • ๐Ÿ”„ Auto-scaling with HorizontalPodAutoscaler
  • ๐Ÿ›ก๏ธ Security hardened (Pod Security Standards, RBAC, NetworkPolicy)
  • ๐Ÿ“Š Prometheus integration via ServiceMonitor
  • ๐Ÿš€ Multi-architecture support (amd64, arm64)
  • ๐Ÿ”’ Azure AD OAuth2 integration
  • ๐ŸŒ Ingress with TLS/SSL support via cert-manager

Quick Access:

  • API & Docs: https://your-domain.com/docs (Swagger UI)
  • Streamlit UI: https://your-domain.com/ui (Web Interface)
  • ReDoc: https://your-domain.com/redoc (API Documentation)
  • Health: https://your-domain.com/health (Health Check)

Resources:

Server Setup

The server can run in two modes:

Quick Start (File Storage - No Database Required)

Perfect for local development, testing, and single-user scenarios:

# Start server immediately - no database needed!
ansible-inspec start-server

# Access endpoints:
# - REST API: http://localhost:8080
# - API Docs: http://localhost:8080/docs

What you get:

  • โœ… Job templates and execution
  • โœ… Profile management
  • โœ… JSON storage in /data directory
  • โŒ No auth/multi-user (use database mode for this)

Production Setup (Database Storage)

For enterprise features with PostgreSQL:

# 1. Start PostgreSQL (Docker recommended)
docker run -d --name ansible-inspec-postgres \
  -e POSTGRES_USER=ansible \
  -e POSTGRES_PASSWORD=ansible \
  -e POSTGRES_DB=ansible_inspec \
  -p 5432:5432 postgres:16-alpine

# 2. Configure environment
cp .env.example .env
# Edit .env and configure:
# - DATABASE__URL (required)
# - ENCRYPTION_KEY (generate with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())")
# - AUTH__JWT_SECRET (for Azure AD)
# - AUTH__ENABLED=true (optional)
# - VCS__ENABLED=true (optional)

# 3. Initialize database
python scripts/init_prisma.py

# 4. Start the server
ansible-inspec start-server

# 5. Verify
curl http://localhost:8080/health
curl http://localhost:8080/docs  # API documentation

Server endpoints:

See Server Documentation and Quick Start Guide for detailed setup.

Docker Deployment

# Using Docker Compose (recommended)
git clone https://github.com/Htunn/ansible-inspec.git
cd ansible-inspec

# Copy and configure environment
cp .env.docker .env
# Edit .env and set POSTGRES_PASSWORD, ENCRYPTION_KEY, etc.

# Start services
docker-compose up -d

# Initialize database
docker-compose exec api prisma db push

# Verify
curl http://localhost:8080/health

See Docker Deployment Guide for production configurations.

Command Line Usage (CLI)

# Execute a profile from Chef Supermarket
ansible-inspec exec dev-sec/linux-baseline --supermarket -i inventory.yml

# Run a local profile
ansible-inspec exec ./my-profile -i inventory.yml

# Convert InSpec profile to Ansible collection
ansible-inspec convert ./my-profile -o ./collections

From Docker Hub

# Pull the latest image
docker pull ghcr.io/htunn/ansible-inspec:latest

# Run with help
docker run --rm ghcr.io/htunn/ansible-inspec:latest --help

See Docker Usage Guide for detailed Docker instructions.

Documentation

Server & API

CLI & Usage

Getting Started

Usage

Server Usage

See Server Documentation for complete server features including:

  • Job templates and workflow orchestration
  • Azure AD authentication
  • VCS integration
  • PostgreSQL database operations
  • API endpoints and examples

CLI Usage

Basic Command

# Run InSpec profile against Ansible inventory
ansible-inspec exec profile.rb -i inventory.yml

# Run compliance tests on specific hosts
ansible-inspec exec compliance/ --target ssh://user@hostname

# Execute with custom reporter and output
ansible-inspec exec profile.rb -i inventory.yml --reporter json --output report.json

# Multiple reporters
ansible-inspec exec profile.rb -i inventory.yml --reporter "cli json:.compliance-reports/report.json html:.compliance-reports/report.html"

Reporter Options

Generate compliance reports in multiple formats:

# JSON report (InSpec schema-compatible)
ansible-inspec exec profile/ -i inventory.yml --reporter json -o .compliance-reports/report.json

# HTML report
ansible-inspec exec profile/ -i inventory.yml --reporter html -o .compliance-reports/report.html

# JUnit XML for CI/CD integration
ansible-inspec exec profile/ -i inventory.yml --reporter junit -o .compliance-reports/junit.xml

# Multiple formats simultaneously
ansible-inspec exec profile/ -i inventory.yml \
  --reporter "cli json:.compliance-reports/results.json html:.compliance-reports/results.html"

Supported Formats:

  • cli - Human-readable console output (default)
  • json - InSpec JSON schema format
  • html - HTML report with summary and details
  • junit - JUnit XML for Jenkins/GitLab CI
  • yaml - YAML format output

Reports are saved to .compliance-reports/ by default, compatible with InSpec tooling including Chef Automate and CI/CD pipelines.

Chef Supermarket Profiles

Leverage 100+ pre-built compliance profiles from Chef Supermarket:

# Run DevSec Linux Baseline against your inventory
ansible-inspec exec dev-sec/linux-baseline --supermarket -i inventory.yml

# Test SSH configuration security
ansible-inspec exec dev-sec/ssh-baseline --supermarket -t ssh://prod-server

# Docker CIS Benchmark compliance
ansible-inspec exec cis-docker-benchmark --supermarket -t docker://container_id

# Web server hardening (Apache, Nginx)
ansible-inspec exec dev-sec/nginx-baseline --supermarket -i web_servers.yml

# Database security (MySQL, PostgreSQL)
ansible-inspec exec dev-sec/postgres-baseline --supermarket -i database.yml

Popular Profiles:

  • dev-sec/linux-baseline - OS hardening (56 controls)
  • dev-sec/ssh-baseline - SSH security (28 controls)
  • cis-docker-benchmark - CIS Docker 1.3.0 (100+ controls)
  • cis-kubernetes-benchmark - Kubernetes security
  • dev-sec/apache-baseline - Apache hardening
  • dev-sec/mysql-baseline - MySQL/MariaDB security
  • dev-sec/nginx-baseline - Nginx hardening
  • dev-sec/postgres-baseline - PostgreSQL security

See Chef Supermarket Guide for complete documentation.

Profile Conversion

Convert InSpec compliance profiles (Ruby) to Ansible collections:

# Convert local InSpec profile
ansible-inspec convert examples/profiles/custom-compliance \
  --namespace example \
  --collection-name custom_compliance

# Convert Chef Supermarket profile
ansible-inspec exec dev-sec/linux-baseline --supermarket --download ./profiles
ansible-inspec convert ./profiles/linux-baseline \
  --namespace devsec \
  --collection-name linux_baseline

# Use the converted collection
ansible-galaxy collection install ./collections/ansible_collections/example/custom_compliance/*.tar.gz
ansible-playbook example.custom_compliance.compliance_check -i inventory.yml

Automatic Compliance Reporting: Converted collections include an auto-enabled callback plugin that generates InSpec-compatible reports in .compliance-reports/:

# Reports are automatically generated when running playbooks
cd collections/ansible_collections/example/custom_compliance
ansible-playbook playbooks/compliance_check.yml -i inventory.yml

# Find reports in .compliance-reports/
ls .compliance-reports/
# 20260108-143022-example.custom_compliance-compliance_check.yml.json
# 20260108-143022-example.custom_compliance-compliance_check.yml.html

Configure reporting in ansible.cfg:

[defaults]
callbacks_enabled = compliance_reporter
callback_result_dir = .compliance-reports

[callback_compliance_reporter]
output_format = json  # or html, junit

Conversion Features:

  • Native Ansible Tasks: Converts standard InSpec resources (file, service, package) to native Ansible modules for better performance
  • Custom Resource Support: Preserves custom InSpec resources from libraries/ directory with InSpec wrapper
  • Full Collection Structure: Generates complete Ansible Galaxy-ready collection with roles, playbooks, and documentation
  • Automatic Detection: Identifies and handles custom resources automatically
  • Metadata Preservation: Maintains profile information, tags, and dependencies in galaxy.yml

Example Use Cases:

  • Convert Chef Supermarket profiles for Ansible-native execution
  • Migrate existing InSpec compliance tests to Ansible collections
  • Publish compliance collections to Ansible Galaxy
  • Integrate InSpec-based compliance into Ansible CI/CD pipelines

See Profile Conversion Guide for complete documentation.

Example Profile

# compliance/ssh_config.rb
describe sshd_config do
  its('PermitRootLogin') { should eq 'no' }
  its('PasswordAuthentication') { should eq 'no' }
end

describe package('telnetd') do
  it { should_not be_installed }
end

Ansible Inventory Integration

# inventory.yml
all:
  hosts:
    web-01:
      ansible_host: 192.168.1.10
    web-02:
      ansible_host: 192.168.1.11
  vars:
    ansible_user: admin
    inspec_profile: compliance/web-server
ansible-inspec exec -i inventory.yml

Quick Start

  1. Install ansible-inspec

    pip install ansible-inspec
    
  2. Create a compliance profile

    ansible-inspec init profile my-compliance
    
  3. Run tests against your infrastructure

    ansible-inspec exec my-compliance -i inventory.yml
    

Documentation

Project Structure

ansible-inspec/
โ”œโ”€โ”€ bin/
โ”‚   โ””โ”€โ”€ ansible-inspec          # Main executable
โ”œโ”€โ”€ lib/
โ”‚   โ”œโ”€โ”€ ansible_inspec/
โ”‚   โ”‚   โ”œโ”€โ”€ ansible_adapter/    # Ansible integration layer
โ”‚   โ”‚   โ”œโ”€โ”€ inspec_adapter/     # InSpec integration layer
โ”‚   โ”‚   โ”œโ”€โ”€ cli/                # CLI interface
โ”‚   โ”‚   โ””โ”€โ”€ core/               # Core functionality
โ”œโ”€โ”€ profiles/                   # Example compliance profiles
โ”œโ”€โ”€ tests/                      # Test suite
โ”œโ”€โ”€ docs/                       # Documentation
โ””โ”€โ”€ examples/                   # Usage examples

How It Works

Ansible-InSpec orchestrates compliance testing by combining Ansible's inventory management with InSpec's testing capabilities:

sequenceDiagram
    participant User
    participant CLI as ansible-inspec CLI
    participant Ansible as Ansible Adapter
    participant InSpec as InSpec Adapter
    participant Inventory as Ansible Inventory
    participant Target as Target Hosts
    
    autonumber
    
    rect rgb(230, 240, 255)
    Note over User,CLI: Initialization Phase
    User->>+CLI: ansible-inspec exec profile.rb -i inventory.yml
    CLI->>CLI: Parse arguments & validate inputs
    CLI->>+Ansible: Load inventory configuration
    end
    
    rect rgb(240, 255, 240)
    Note over Ansible,Inventory: Inventory Processing
    Ansible->>+Inventory: Parse YAML inventory
    Inventory-->>-Ansible: Host groups & variables
    Ansible->>Ansible: Build host list with connection details
    Note right of Ansible: Supports SSH, WinRM,<br/>Docker, local connections
    Ansible-->>-CLI: Return target hosts with URIs
    end
    
    rect rgb(255, 245, 230)
    Note over CLI,InSpec: Profile Validation
    CLI->>+InSpec: Load InSpec profile
    InSpec->>InSpec: Validate profile structure
    InSpec->>InSpec: Parse controls & tests
    InSpec-->>-CLI: Profile ready
    end
    
    rect rgb(255, 240, 245)
    Note over CLI,Target: Execution Phase (Parallel)
    par For each target host
        CLI->>+InSpec: Execute profile on host-1
        InSpec->>+Target: SSH/WinRM connection
        Target-->>-InSpec: System information
        InSpec->>Target: Run compliance checks
        Target-->>InSpec: Check results
        InSpec->>InSpec: Aggregate test results
        InSpec-->>-CLI: Host-1 results
    and
        CLI->>+InSpec: Execute profile on host-2
        InSpec->>+Target: SSH/WinRM connection
        Target-->>-InSpec: System information
        InSpec->>Target: Run compliance checks
        Target-->>InSpec: Check results
        InSpec->>InSpec: Aggregate test results
        InSpec-->>-CLI: Host-2 results
    and
        CLI->>+InSpec: Execute profile on host-N
        InSpec->>+Target: SSH/WinRM connection
        Target-->>-InSpec: System information
        InSpec->>Target: Run compliance checks
        Target-->>InSpec: Check results
        InSpec->>InSpec: Aggregate test results
        InSpec-->>-CLI: Host-N results
    end
    end
    
    rect rgb(245, 245, 255)
    Note over CLI,User: Results & Reporting
    CLI->>CLI: Aggregate all host results
    CLI->>CLI: Generate compliance report
    CLI-->>-User: Display results (JSON/CLI/HTML)
    
    alt All tests passed
        Note over User: โœ… Infrastructure compliant
    else Some tests failed
        Note over User: โŒ Non-compliance detected<br/>Review failed controls
    end
    end

Workflow Explanation

  1. Initialization: User runs ansible-inspec with a profile and inventory
  2. Inventory Loading: Ansible adapter parses the YAML inventory and extracts:
    • Host definitions and groups
    • Connection details (SSH keys, passwords, ports)
    • Variables and host-specific configurations
  3. Profile Validation: InSpec adapter loads and validates the compliance profile
  4. Parallel Execution: Tests run simultaneously across all target hosts:
    • Establishes connections using Ansible's connection URIs
    • Executes InSpec controls on each host
    • Collects pass/fail results for each control
  5. Results Aggregation: Combines results from all hosts into unified report
  6. Output: Presents compliance status in requested format (JSON, CLI, HTML)

Connection Flow Details

The tool supports multiple connection types automatically detected from your Ansible inventory:

  • SSH: ssh://user@hostname:port with key or password authentication
  • WinRM: winrm://user@hostname:port for Windows hosts
  • Docker: docker://container_id for containerized targets
  • Local: local:// for testing the local system

Upstream Projects

This project builds upon two excellent open-source projects:

Ansible

InSpec

Docker Usage

# Initialize a new InSpec profile
docker run --rm -v $(pwd):/workspace ghcr.io/htunn/ansible-inspec:latest \
  init profile my-compliance-tests

# Run compliance tests with Ansible inventory
docker run --rm \
  -v $(pwd):/workspace \
  -v ~/.ssh:/home/ansibleinspec/.ssh:ro \
  ghcr.io/htunn/ansible-inspec:latest \
  exec /workspace/profiles/cis-benchmark \
  -i /workspace/inventory.yml

# Available tags: latest, v0.1.0, v0.2.0, etc.
docker run --rm ghcr.io/htunn/ansible-inspec:v0.1.0 --version

See Docker Usage Guide for more examples.

Development

Quick Start

# Clone repository
git clone https://github.com/Htunn/ansible-inspec.git
cd ansible-inspec

# Install with dev dependencies
make dev-install

# Run tests
make test

# Format code
make format

# Build package
make build

See QUICKSTART.md for detailed development setup.

Publishing

This project uses automated publishing via GitHub Actions:

  1. PyPI: Triggered by git tags (e.g., v0.1.0)
  2. Docker Hub: Triggered by git tags, builds multi-arch images

See Publishing Guide for details.

License

This project is licensed under the GNU General Public License v3.0 (GPL-3.0).

Since this project combines components from:

  • Ansible (GPL-3.0 licensed)
  • InSpec (Apache-2.0 licensed)

The combined work must be distributed under GPL-3.0, as it is the more restrictive license. The Apache-2.0 license is compatible with GPL-3.0, allowing this combination.

See LICENSE for the full license text and NOTICE for detailed attribution and license compatibility information.

Why GPL-3.0?

When combining GPL-licensed code (Ansible) with Apache-2.0 licensed code (InSpec), the GPL license governs the combined work. This ensures:

  • Compliance with Ansible's GPL-3.0 licensing requirements
  • Proper attribution to both upstream projects
  • Legal compatibility between the two licenses
  • Protection of user freedoms as intended by both projects

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Code of Conduct

This project adheres to the codes of conduct from both upstream projects:

Support

Acknowledgments

Special thanks to:

  • The Ansible team and community at Red Hat
  • The InSpec team and community at Progress Chef
  • All contributors to both upstream projects

Disclaimer

ansible-inspec is an independent open-source project and is not officially affiliated with, endorsed by, or supported by Red Hat, Inc. (Ansible) or Progress Software Corporation (Chef InSpec).

Trademarks:

  • "Ansible" is a registered trademark of Red Hat, Inc.
  • "InSpec" is a trademark of Progress Software Corporation.

This project integrates with and builds upon these technologies under their respective open source licenses:

The use of these names in this project is purely descriptive to indicate compatibility and integration. For official Ansible products and support, visit Red Hat Ansible. For official InSpec products and support, visit Chef InSpec.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ansible_inspec-0.2.12.tar.gz (211.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ansible_inspec-0.2.12-py3-none-any.whl (133.9 kB view details)

Uploaded Python 3

File details

Details for the file ansible_inspec-0.2.12.tar.gz.

File metadata

  • Download URL: ansible_inspec-0.2.12.tar.gz
  • Upload date:
  • Size: 211.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ansible_inspec-0.2.12.tar.gz
Algorithm Hash digest
SHA256 95e497957e8ce311ae6174b4482fd434f2daac7c0c3938441c5dea00274f1668
MD5 1263942481aebc215eeda70fc0a0a805
BLAKE2b-256 742ba55eb6daee6cb3d3ec191a5903ea4cfe5ca4671632d100e073fe974bfdfb

See more details on using hashes here.

Provenance

The following attestation bundles were made for ansible_inspec-0.2.12.tar.gz:

Publisher: publish.yml on Htunn/ansible-inspec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ansible_inspec-0.2.12-py3-none-any.whl.

File metadata

  • Download URL: ansible_inspec-0.2.12-py3-none-any.whl
  • Upload date:
  • Size: 133.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ansible_inspec-0.2.12-py3-none-any.whl
Algorithm Hash digest
SHA256 31925f2cac69c73529b4d024e207149963f756ef0ed8b7c6459cca8d23e9a3d0
MD5 9df7fbd39ed1cf4b3e9f86248c6bdcf1
BLAKE2b-256 a6ce8c8dd92fd4677ced28f46f535662cbba9dbff22f73697b350357f50824fd

See more details on using hashes here.

Provenance

The following attestation bundles were made for ansible_inspec-0.2.12-py3-none-any.whl:

Publisher: publish.yml on Htunn/ansible-inspec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page