<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: automation-scripting
description: >-
  Security automation with Ansible CIS hardening, Terraform IaC, Docker Compose,
  Python/Bash security scripts, SOPS/Vault secrets management, borgmatic backup,
  and Claude Code hooks/subagents. Use when asked for infrastructure-as-code
  security, CI/CD pipeline hardening, secret management, backup automation,
  or automated security assessment orchestration.
domain: cybersecurity
subdomain: automation-scripting
tags:
  - ansible
  - terraform
  - docker
  - iac-security
  - secrets-management
  - ci-cd
  - cis-benchmarks
  - claude-code
  - backup
  - hardening
version: "1.1"
author: defconxt
license: AGPL-3.0
compatibility: >-
  Ansible 2.14+, Terraform 1.5+, Docker 24+, Python 3.10+, sops 3.8+, age,
  borgmatic 1.8+. Claude Code hooks require Claude Code CLI.
metadata:
  mitre-attack: ["T1059", "T1078", "T1098", "T1133", "T1543"]
  nist-csf: ["PR.IP-1", "PR.IP-4", "PR.MA-1", "PR.DS-1", "PR.DS-2"]
  cis-controls: ["4.1", "5.2", "5.4", "6.1", "6.2", "16.1"]
---

# Security Automation and Scripting

## When to Use

- Ansible CIS hardening playbooks and roles for Linux/Windows
- Terraform infrastructure-as-code security patterns and scanning
- Docker Compose secure deployment with non-root, read-only, capability dropping
- Python/Bash security scripts (Impacket, Scapy, Paramiko, log parsing)
- SOPS/Ansible Vault secrets management and encrypted backup with borgmatic
- Claude Code security hooks, subagent orchestration, and assessment automation
- CI/CD pipeline hardening and IaC static analysis (tfsec, checkov, Trivy)

## Prerequisites

- Ansible 2.14+ with `ansible.posix` and `community.general` collections
- Terraform 1.5+ with tfsec and checkov for static analysis
- Docker 24+ and Docker Compose v2
- Python 3.10+ with type hints; sops 3.8+ with age key pairs
- Claude Code CLI for hook and subagent patterns

## Quick Reference

### Example: Ansible CIS Hardening

```yaml
# playbook: cis-level1.yml
- hosts: all
  become: true
  tasks:
    - name: Ensure SSH root login is disabled
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^PermitRootLogin'
        line: 'PermitRootLogin no'
      notify: restart sshd

    - name: Ensure IP forwarding is disabled
      sysctl:
        name: net.ipv4.ip_forward
        value: '0'
        state: present
```

### Example: Terraform Security Group

```hcl
resource "aws_security_group" "web" {
  name   = "web-sg"
  vpc_id = var.vpc_id

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
```


| Task | Command |
|------|---------|
| CIS kernel module disable | `ansible.builtin.lineinfile dest=/etc/modprobe.d/cis.conf line="install cramfs /bin/false"` |
| Sysctl hardening | `ansible.posix.sysctl name=net.ipv4.conf.all.rp_filter value=1 sysctl_set=true` |
| SOPS encrypt (age) | `sops --encrypt --age age1... secrets.yaml > secrets.enc.yaml` |
| SOPS inject to env | `sops exec-env secrets.enc.yaml 'env'` |
| Borgmatic backup | `borgmatic --config /etc/borgmatic/config.yaml create --stats` |
| Borgmatic restore | `borgmatic extract --archive latest --path /etc/` |
| Ansible vault encrypt | `ansible-vault encrypt_string 'secretvalue' --name 'var_name'` |
| Terraform scan | `checkov -d . --framework terraform` / `tfsec .` |
| Docker secret | `docker secret create db_password ./db_password.txt` |
| Trivy image scan | `trivy image --severity HIGH,CRITICAL --exit-code 1 myapp:latest` |
| Claude Code hook | `PreToolUse` — block `rm -rf` and `.env` reads before tool fires |
| Subagent spawn | `claude -p "run nmap scan on 10.0.0.0/24" --model haiku` |

## Workflow

### 1. CIS Hardening Deployment

1. Verify targets: `ansible-inventory --graph -i inventory/`
2. Preview changes: `ansible-playbook cis-harden.yml --check --diff -i inventory/prod`
3. Apply kernel module blacklisting (CIS 1.x), sysctl hardening (CIS 3.x)
4. Apply firewall rules (CIS 4.x), SSH hardening (CIS 5.x)
5. Enable audit logging (CIS 6.x), verify idempotency with final `--check`

Read `references/ansible-cis-hardening.md` for full role patterns, sysctl values, and SSH template validation.

### 2. Secure Infrastructure Provisioning

1. Init remote state: `terraform init` with S3 + KMS + DynamoDB lock
2. Static analysis gate: `tfsec . && checkov -d .` — block on HIGH/CRITICAL
3. Plan review: `terraform plan -out=tfplan` — check for `0.0.0.0/0` ingress, unencrypted storage
4. Apply behind approval gate (Atlantis or manual)
5. Post-deploy verification: check encryption, IAM credential report

Read `references/terraform-iac-security.md` for IAM policies, S3 encryption, KMS rotation, and Terragrunt patterns.

### 3. Container Security Deployment

1. Write Compose with `user`, `read_only`, `cap_drop: [ALL]`, `security_opt: [no-new-privileges:true]`
2. Use Docker secrets for sensitive values (never environment variables for passwords)
3. Set `internal: true` networks for backend services
4. Scan images with Trivy before deployment
5. Configure daemon with `no-new-privileges`, `userland-proxy: false`

Read `references/docker-container-security.md` for full Compose patterns, Pi-hole config, and Ansible Docker roles.

### 4. Security Assessment Automation (Claude Code)

1. Write `.claude/commands/sec-assess.md` with target, scope, output format
2. Spawn recon subagent (haiku + Bash) for port scanning
3. Spawn vuln subagent (sonnet + Read + Bash) for CVE mapping
4. `PreToolUse` hook blocks destructive commands; `PostToolUse` logs to audit trail
5. Report agent formats findings as FINDING-001 blocks with CVSS + ATT&CK IDs

Read `references/security-scripting.md` for Impacket, Scapy, Paramiko patterns, and Claude Code hook/subagent architecture.

### 5. Secrets Management

1. Generate age key pair: `age-keygen -o ~/.config/sops/age/keys.txt`
2. Configure `.sops.yaml` with `creation_rules` and path regex
3. Encrypt: `sops --encrypt secrets/prod.yaml > secrets/prod.enc.yaml`
4. Runtime injection: `sops exec-env secrets/prod.enc.yaml './app'`
5. Backup encrypted with borgmatic: configure repos, retention, and pre/post hooks

Read `references/secrets-management.md` for SOPS/age/KMS patterns, Ansible Vault rotation, and borgmatic config.

## Verification

- CIS hardening: final `ansible-playbook --check` returns zero changes
- Terraform: `tfsec` and `checkov` return zero HIGH/CRITICAL findings
- Docker: `docker inspect` confirms non-root user, dropped capabilities
- Secrets: `sops --decrypt` with correct key succeeds; plaintext never on disk
- Borgmatic: `borgmatic check` validates repository integrity
