Initial commit
This commit is contained in:
428
commands/ansible-full-review.md
Normal file
428
commands/ansible-full-review.md
Normal file
@@ -0,0 +1,428 @@
|
||||
---
|
||||
description: Complete code quality and security review
|
||||
argument-hint: Optional code to review
|
||||
---
|
||||
|
||||
# Complete Ansible Review
|
||||
|
||||
You are conducting a comprehensive Ansible review including both code quality and security using the ansible-orchestrator agent to coordinate multiple reviewer agents.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Identify Review Scope
|
||||
|
||||
Determine what needs comprehensive review:
|
||||
- **New production code**: Before initial production deployment
|
||||
- **Major changes**: Significant refactoring or new features
|
||||
- **Pre-release**: Before tagging a release
|
||||
- **Compliance audit**: Regulatory compliance check
|
||||
- **Security incident**: Post-incident code review
|
||||
- **Regular audit**: Scheduled quarterly review
|
||||
|
||||
### 2. Gather Code and Context
|
||||
|
||||
If not specified, ask for:
|
||||
- **Code to review**:
|
||||
- File paths or directories
|
||||
- Role names
|
||||
- Entire project
|
||||
- Git commit range (e.g., main..feature-branch)
|
||||
- **Code type**:
|
||||
- Roles, playbooks, collections
|
||||
- Inventory and variables
|
||||
- Custom modules or plugins
|
||||
- **Environment details**:
|
||||
- Target environment (production/staging/development)
|
||||
- Criticality level (mission-critical/important/standard)
|
||||
- Number of managed hosts
|
||||
- Infrastructure type (bare metal/VMs/cloud/containers)
|
||||
- **Compliance requirements**:
|
||||
- PCI-DSS, HIPAA, GDPR, SOC 2
|
||||
- CIS Benchmarks
|
||||
- Company-specific policies
|
||||
- Industry standards
|
||||
- **Specific concerns**:
|
||||
- Known issues to verify
|
||||
- Areas of technical debt
|
||||
- Recent changes to review
|
||||
- Performance bottlenecks
|
||||
- **Review depth**:
|
||||
- Quick review (high/critical only)
|
||||
- Standard review (high/medium)
|
||||
- Comprehensive review (all findings)
|
||||
- Compliance audit (focus on compliance)
|
||||
|
||||
### 3. Pre-Review Preparation
|
||||
|
||||
Run automated scans before launching agents:
|
||||
|
||||
```bash
|
||||
# Syntax validation
|
||||
find roles/ playbooks/ -name "*.yml" -exec ansible-playbook {} --syntax-check \;
|
||||
|
||||
# ansible-lint (all profiles)
|
||||
ansible-lint --profile production roles/
|
||||
ansible-lint --profile security roles/
|
||||
|
||||
# Secret scanning
|
||||
trufflehog filesystem . --only-verified
|
||||
git secrets --scan
|
||||
|
||||
# Check vault files encrypted
|
||||
find . -name "vault*.yml" -exec file {} \; | grep -v "data"
|
||||
|
||||
# Complexity analysis
|
||||
find roles/ -name "*.yml" -exec wc -l {} \; | sort -rn | head -20
|
||||
|
||||
# Inventory verification
|
||||
ansible-inventory -i inventory/production --graph
|
||||
ansible-inventory -i inventory/production --list
|
||||
```
|
||||
|
||||
### 4. Launch Orchestrator
|
||||
|
||||
Launch **ansible-orchestrator** to coordinate both reviews:
|
||||
|
||||
```
|
||||
"Conduct comprehensive review of Ansible code at [location].
|
||||
|
||||
**Code Context**:
|
||||
- Type: [roles/playbooks/collection]
|
||||
- Environment: [production/staging/development]
|
||||
- Criticality: [mission-critical/important/standard]
|
||||
- Target infrastructure: [description]
|
||||
|
||||
**Compliance Requirements**:
|
||||
- [List: PCI-DSS, HIPAA, GDPR, SOC 2, etc.]
|
||||
- [Company-specific policies]
|
||||
|
||||
**Review Scope**:
|
||||
- Code quality and best practices (ansible-code-reviewer)
|
||||
- Security vulnerabilities and compliance (ansible-security-reviewer)
|
||||
- Both reviews should run in parallel
|
||||
|
||||
**Focus Areas**:
|
||||
- [List specific concerns if any]
|
||||
- Known issues: [list if any]
|
||||
- Recent changes: [git commit range if applicable]
|
||||
|
||||
**Review Depth**: [Quick/Standard/Comprehensive/Compliance]
|
||||
|
||||
Coordinate both reviews and synthesize findings into:
|
||||
1. Executive summary
|
||||
2. Combined findings by severity
|
||||
3. Prioritized action plan
|
||||
4. Compliance status per requirement"
|
||||
```
|
||||
|
||||
### 5. Orchestrator Review Process
|
||||
|
||||
The orchestrator will:
|
||||
|
||||
**Phase 1: Parallel Reviews**
|
||||
- Launch **ansible-code-reviewer** for quality review
|
||||
- Launch **ansible-security-reviewer** for security review
|
||||
- Both agents work in parallel
|
||||
|
||||
**Phase 2: Analysis**
|
||||
- Collect findings from both agents
|
||||
- Identify overlapping issues
|
||||
- Cross-reference findings
|
||||
- Categorize by severity
|
||||
|
||||
**Phase 3: Synthesis**
|
||||
- Create unified findings list
|
||||
- Prioritize by severity and impact
|
||||
- Generate compliance matrix
|
||||
- Create remediation roadmap
|
||||
|
||||
### 6. Analyze Combined Findings
|
||||
|
||||
Review categorizes all findings by severity:
|
||||
|
||||
**Critical** (Block all deployment):
|
||||
- **Code**: Syntax errors, idempotency violations causing data loss
|
||||
- **Security**: Hardcoded credentials, command injection, exposed secrets
|
||||
- **Compliance**: Violations of mandatory requirements
|
||||
- **Impact**: Production outages, data breaches, compliance penalties
|
||||
|
||||
**High** (Fix before production):
|
||||
- **Code**: Non-idempotent operations, improper module usage
|
||||
- **Security**: Missing encryption, excessive privileges, weak permissions
|
||||
- **Compliance**: Violations of important requirements
|
||||
- **Impact**: Reliability issues, security risks, audit findings
|
||||
|
||||
**Medium** (Address within sprint):
|
||||
- **Code**: Poor organization, suboptimal performance
|
||||
- **Security**: Missing audit logs, unpinned versions
|
||||
- **Compliance**: Best practice violations
|
||||
- **Impact**: Technical debt, maintainability issues
|
||||
|
||||
**Low** (Best practice improvements):
|
||||
- **Code**: Style inconsistencies, documentation gaps
|
||||
- **Security**: Could use stricter controls
|
||||
- **Compliance**: Documentation improvements
|
||||
- **Impact**: Code quality, team efficiency
|
||||
|
||||
### 7. Compliance Assessment
|
||||
|
||||
Generate compliance matrix:
|
||||
|
||||
```
|
||||
Requirement | Status | Findings | Priority
|
||||
------------|--------|----------|----------
|
||||
PCI-DSS 3.4 | FAIL | Secrets in logs | Critical
|
||||
PCI-DSS 7.1 | PASS | Access controls OK | -
|
||||
PCI-DSS 8.2 | FAIL | Weak passwords | High
|
||||
HIPAA §164 | FAIL | PHI in logs | Critical
|
||||
GDPR Art 32 | PASS | Encryption OK | -
|
||||
SOC 2 CC6.1 | FAIL | No MFA | High
|
||||
```
|
||||
|
||||
### 8. Create Remediation Plan
|
||||
|
||||
Orchestrator creates prioritized action plan:
|
||||
|
||||
**Immediate (0-24 hours)** - Block deployment:
|
||||
1. [Critical Code Issue] - Location, Impact, Fix
|
||||
2. [Critical Security Issue] - Location, Impact, Fix
|
||||
3. [Critical Compliance Issue] - Location, Impact, Fix
|
||||
|
||||
**Short-term (1-7 days)** - Before production:
|
||||
1. [High Priority Issues] - Categorized and prioritized
|
||||
2. [High Security Issues]
|
||||
3. [High Compliance Issues]
|
||||
|
||||
**Medium-term (1-4 weeks)** - Address in sprint:
|
||||
1. [Medium Priority Issues] - Grouped by area
|
||||
2. [Technical debt items]
|
||||
3. [Performance improvements]
|
||||
|
||||
**Long-term (1-3 months)** - Continuous improvement:
|
||||
1. [Low priority improvements]
|
||||
2. [Architecture improvements]
|
||||
3. [Documentation and training]
|
||||
4. [Automation and tooling]
|
||||
|
||||
## Output Format
|
||||
|
||||
### Comprehensive Review Report
|
||||
|
||||
#### Executive Summary
|
||||
|
||||
**Overall Assessment**:
|
||||
- **Code Quality**: [Excellent/Good/Needs Improvement/Poor]
|
||||
- **Security Posture**: [Strong/Adequate/Weak/Critical]
|
||||
- **Compliance Status**: [Compliant/Mostly Compliant/Non-Compliant]
|
||||
- **Deployment Recommendation**: [✓ Approve / ⚠ Conditional / ✗ Block]
|
||||
|
||||
**Findings Summary**:
|
||||
- Critical Issues: [count] - MUST FIX BEFORE DEPLOYMENT
|
||||
- High Priority: [count] - Fix before production
|
||||
- Medium Priority: [count] - Address in sprint
|
||||
- Low Priority: [count] - Continuous improvement
|
||||
|
||||
**Key Risks Identified**:
|
||||
1. [Most critical risk with impact]
|
||||
2. [Second critical risk]
|
||||
3. [Third critical risk]
|
||||
|
||||
**Recommendations**:
|
||||
1. [Primary recommendation]
|
||||
2. [Secondary recommendation]
|
||||
3. [Tertiary recommendation]
|
||||
|
||||
#### Combined Findings by Severity
|
||||
|
||||
**[CRITICAL] Findings**
|
||||
|
||||
**Code Quality**:
|
||||
```
|
||||
[CRITICAL] Idempotency: Non-idempotent database operation
|
||||
Location: roles/database/tasks/restore.yml:42
|
||||
Issue: Shell command modifies database without idempotency check
|
||||
Impact: Data loss on repeated runs
|
||||
Fix: Use database module with state management
|
||||
```
|
||||
|
||||
**Security**:
|
||||
```
|
||||
[CRITICAL] Credential Management: Hardcoded API Key
|
||||
Location: roles/api/defaults/main.yml:15
|
||||
Issue: API key in plain text in version control
|
||||
Impact: Exposed credentials, PCI-DSS violation
|
||||
Fix: Remove from code, use Ansible Vault
|
||||
```
|
||||
|
||||
**[HIGH] Findings**
|
||||
|
||||
[Similar format for High priority findings]
|
||||
|
||||
**[MEDIUM] Findings**
|
||||
|
||||
[Similar format for Medium priority findings]
|
||||
|
||||
**[LOW] Findings**
|
||||
|
||||
[Similar format for Low priority findings]
|
||||
|
||||
#### Compliance Assessment Matrix
|
||||
|
||||
**PCI-DSS Compliance**:
|
||||
- ✗ Requirement 3.4: Cardholder data in logs (FAIL - Critical)
|
||||
- ✓ Requirement 4.1: Encrypted transmission (PASS)
|
||||
- ✗ Requirement 7.1: Access controls insufficient (FAIL - High)
|
||||
- ✗ Requirement 8.2: Weak password policy (FAIL - High)
|
||||
- ✓ Requirement 10.1: Audit trails present (PASS)
|
||||
|
||||
**Overall PCI-DSS**: ✗ NON-COMPLIANT (3 failures)
|
||||
|
||||
**HIPAA Compliance**:
|
||||
- ✗ §164.312(a)(1): PHI in logs (FAIL - Critical)
|
||||
- ✓ §164.312(a)(2): Encryption (PASS)
|
||||
- ✗ §164.312(d): Audit controls missing (FAIL - High)
|
||||
|
||||
**Overall HIPAA**: ✗ NON-COMPLIANT (2 failures)
|
||||
|
||||
#### Remediation Roadmap
|
||||
|
||||
**Phase 1: Immediate (0-24 hours)**
|
||||
|
||||
BLOCK DEPLOYMENT until fixed:
|
||||
|
||||
1. **[Code] Fix idempotency violation**
|
||||
- Location: roles/database/tasks/restore.yml:42
|
||||
- Action: Replace shell with postgresql_db module
|
||||
- Owner: [Developer name]
|
||||
- Verification: Run twice in check mode, both should be idempotent
|
||||
|
||||
2. **[Security] Remove hardcoded API key**
|
||||
- Location: roles/api/defaults/main.yml:15
|
||||
- Action: Remove from code, add to vault, use {{ vault_api_key }}
|
||||
- Owner: [Security team]
|
||||
- Verification: Git history scan, no secrets found
|
||||
|
||||
3. **[Security] Fix PHI in logs**
|
||||
- Location: roles/patient/tasks/main.yml:*
|
||||
- Action: Add no_log: true to all PHI-handling tasks
|
||||
- Owner: [Compliance team]
|
||||
- Verification: Test run, no PHI in logs
|
||||
|
||||
**Phase 2: Short-term (1-7 days)**
|
||||
|
||||
Required before production:
|
||||
|
||||
1. Fix all High priority code issues (5 issues)
|
||||
2. Implement proper access controls
|
||||
3. Strengthen password policy
|
||||
4. Add audit logging
|
||||
5. Re-review after fixes
|
||||
|
||||
**Phase 3: Medium-term (1-4 weeks)**
|
||||
|
||||
During sprint:
|
||||
|
||||
1. Refactor complex roles (technical debt)
|
||||
2. Improve test coverage
|
||||
3. Update documentation
|
||||
4. Performance optimization
|
||||
|
||||
**Phase 4: Long-term (1-3 months)**
|
||||
|
||||
Continuous improvement:
|
||||
|
||||
1. Migrate to external secret management
|
||||
2. Implement automated security scanning
|
||||
3. Regular compliance audits
|
||||
4. Team training on secure coding
|
||||
|
||||
#### Testing and Validation
|
||||
|
||||
**After Critical Fixes**:
|
||||
```bash
|
||||
# Re-run automated checks
|
||||
ansible-lint --profile production roles/
|
||||
ansible-lint --profile security roles/
|
||||
trufflehog filesystem . --only-verified
|
||||
|
||||
# Verify idempotency
|
||||
ansible-playbook playbook.yml --check
|
||||
ansible-playbook playbook.yml --check # Run twice
|
||||
|
||||
# Security validation
|
||||
git log -p | grep -i "password\|secret\|key" # Should find nothing
|
||||
find . -name "vault*.yml" -exec file {} \; # Should show "data"
|
||||
|
||||
# Test in staging
|
||||
ansible-playbook playbook.yml -i inventory/staging -vv
|
||||
```
|
||||
|
||||
**Before Production Deployment**:
|
||||
```bash
|
||||
# Full test suite
|
||||
ansible-playbook playbook.yml --syntax-check
|
||||
ansible-lint --profile production roles/
|
||||
ansible-playbook playbook.yml -i inventory/staging
|
||||
molecule test # For role testing
|
||||
|
||||
# Re-review
|
||||
# Launch full review again to verify all fixes
|
||||
```
|
||||
|
||||
#### Deployment Decision
|
||||
|
||||
**Current Status**: [✓ Approved / ⚠ Conditional / ✗ BLOCKED]
|
||||
|
||||
**Conditions for Approval** (if conditional):
|
||||
- [ ] Fix all Critical issues
|
||||
- [ ] Fix High priority security issues
|
||||
- [ ] Address compliance violations
|
||||
- [ ] Pass automated testing
|
||||
- [ ] Re-review completed and passed
|
||||
|
||||
**Blocking Issues** (if blocked):
|
||||
1. [Issue preventing deployment]
|
||||
2. [Issue preventing deployment]
|
||||
3. [Issue preventing deployment]
|
||||
|
||||
**Sign-off Requirements**:
|
||||
- [ ] Code quality review passed
|
||||
- [ ] Security review passed
|
||||
- [ ] Compliance requirements met
|
||||
- [ ] Testing completed successfully
|
||||
- [ ] Deployment runbook prepared
|
||||
- [ ] Rollback plan documented
|
||||
|
||||
## Best Practices
|
||||
|
||||
**Pre-Review**:
|
||||
- Run all automated scans first
|
||||
- Fix obvious issues before agent review
|
||||
- Prepare context and requirements
|
||||
- Identify stakeholders for sign-off
|
||||
|
||||
**During Review**:
|
||||
- Provide complete context to orchestrator
|
||||
- Specify all compliance requirements
|
||||
- Note any constraints or special concerns
|
||||
- Allow parallel reviews to complete
|
||||
|
||||
**Post-Review**:
|
||||
- Address Critical issues immediately
|
||||
- Plan High priority fixes before production
|
||||
- Document decisions and rationale
|
||||
- Schedule re-review after fixes
|
||||
|
||||
**Continuous Improvement**:
|
||||
- Integrate reviews in CI/CD pipeline
|
||||
- Regular scheduled reviews (quarterly)
|
||||
- Track metrics (issues found, time to fix)
|
||||
- Team training based on findings
|
||||
- Update standards based on lessons learned
|
||||
|
||||
**Sign-off Process**:
|
||||
- Development lead: Code quality
|
||||
- Security team: Security review
|
||||
- Compliance officer: Compliance requirements
|
||||
- Operations: Deployment readiness
|
||||
- All stakeholders before production deployment
|
||||
872
commands/ansible-project-init.md
Normal file
872
commands/ansible-project-init.md
Normal file
@@ -0,0 +1,872 @@
|
||||
---
|
||||
description: Initialize new Ansible project structure
|
||||
argument-hint: Optional project requirements
|
||||
---
|
||||
|
||||
# Ansible Project Initialization
|
||||
|
||||
You are setting up a new Ansible project with proper structure, configuration, and best practices using the ansible-developer agent.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Gather Project Requirements
|
||||
|
||||
If not specified, ask for:
|
||||
- **Project information**:
|
||||
- Project name and purpose
|
||||
- Team or organization name
|
||||
- Git repository location
|
||||
- **Target infrastructure**:
|
||||
- Target platforms (Linux, Windows, network devices)
|
||||
- Number of environments (dev, staging, production)
|
||||
- Approximate number of hosts per environment
|
||||
- **Initial roles needed**:
|
||||
- Application roles (web server, database, app)
|
||||
- Infrastructure roles (common, security, monitoring)
|
||||
- Third-party roles to include
|
||||
- **Security setup**:
|
||||
- Ansible Vault for secrets (yes/no)
|
||||
- Vault password file location or method
|
||||
- Separate vaults per environment
|
||||
- **Testing setup**:
|
||||
- Include Molecule testing (yes/no)
|
||||
- Testing platforms (Docker, Vagrant, cloud)
|
||||
- CI/CD integration planned
|
||||
- **Standards and requirements**:
|
||||
- ansible-lint configuration
|
||||
- Pre-commit hooks
|
||||
- Documentation requirements
|
||||
|
||||
### 2. Create Directory Structure
|
||||
|
||||
Launch **ansible-developer** to create standard Ansible project structure:
|
||||
|
||||
```
|
||||
project-name/
|
||||
├── ansible.cfg # Ansible configuration
|
||||
├── .gitignore # Git ignore patterns
|
||||
├── .ansible-lint # Lint configuration
|
||||
├── README.md # Project documentation
|
||||
├── requirements.yml # Galaxy role dependencies
|
||||
├── requirements.txt # Python dependencies
|
||||
│
|
||||
├── inventory/
|
||||
│ ├── production/
|
||||
│ │ ├── hosts.yml # Production inventory
|
||||
│ │ └── group_vars/
|
||||
│ │ └── all/
|
||||
│ │ ├── vars.yml # Production variables
|
||||
│ │ └── vault.yml # Encrypted secrets
|
||||
│ ├── staging/
|
||||
│ │ ├── hosts.yml
|
||||
│ │ └── group_vars/
|
||||
│ └── development/
|
||||
│ ├── hosts.yml
|
||||
│ └── group_vars/
|
||||
│
|
||||
├── roles/
|
||||
│ ├── common/ # Common role
|
||||
│ │ ├── README.md
|
||||
│ │ ├── defaults/main.yml
|
||||
│ │ ├── handlers/main.yml
|
||||
│ │ ├── tasks/main.yml
|
||||
│ │ ├── templates/
|
||||
│ │ ├── files/
|
||||
│ │ └── vars/main.yml
|
||||
│ └── .gitkeep
|
||||
│
|
||||
├── playbooks/
|
||||
│ ├── site.yml # Master playbook
|
||||
│ ├── provision.yml # Provisioning playbook
|
||||
│ ├── deploy.yml # Deployment playbook
|
||||
│ └── maintenance.yml # Maintenance playbook
|
||||
│
|
||||
├── group_vars/
|
||||
│ └── all.yml # Global variables
|
||||
│
|
||||
├── host_vars/ # Host-specific variables
|
||||
│ └── .gitkeep
|
||||
│
|
||||
├── files/ # Static files
|
||||
│ └── .gitkeep
|
||||
│
|
||||
├── templates/ # Global templates
|
||||
│ └── .gitkeep
|
||||
│
|
||||
├── filter_plugins/ # Custom filters
|
||||
│ └── .gitkeep
|
||||
│
|
||||
├── library/ # Custom modules
|
||||
│ └── .gitkeep
|
||||
│
|
||||
└── molecule/ # Testing (optional)
|
||||
└── default/
|
||||
├── molecule.yml
|
||||
├── converge.yml
|
||||
└── verify.yml
|
||||
```
|
||||
|
||||
### 3. Configure ansible.cfg
|
||||
|
||||
Create optimized ansible.cfg:
|
||||
|
||||
```ini
|
||||
[defaults]
|
||||
# Inventory
|
||||
inventory = ./inventory/development
|
||||
|
||||
# Connection
|
||||
host_key_checking = False
|
||||
timeout = 30
|
||||
forks = 20
|
||||
|
||||
# Output
|
||||
stdout_callback = yaml
|
||||
callbacks_enabled = profile_tasks, timer
|
||||
display_skipped_hosts = False
|
||||
|
||||
# Roles
|
||||
roles_path = ./roles:~/.ansible/roles:/usr/share/ansible/roles
|
||||
|
||||
# Collections
|
||||
collections_paths = ./collections:~/.ansible/collections:/usr/share/ansible/collections
|
||||
|
||||
# Logs
|
||||
log_path = ./ansible.log
|
||||
|
||||
# Vault
|
||||
vault_password_file = ./.vault-pass # Do not commit this file!
|
||||
|
||||
# Retry
|
||||
retry_files_enabled = False
|
||||
|
||||
[privilege_escalation]
|
||||
become = True
|
||||
become_method = sudo
|
||||
become_user = root
|
||||
become_ask_pass = False
|
||||
|
||||
[ssh_connection]
|
||||
pipelining = True
|
||||
control_path = /tmp/ansible-ssh-%%h-%%p-%%r
|
||||
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
|
||||
|
||||
[inventory]
|
||||
enable_plugins = yaml, ini, script
|
||||
```
|
||||
|
||||
### 4. Create .gitignore
|
||||
|
||||
Protect sensitive files:
|
||||
|
||||
```gitignore
|
||||
# Ansible
|
||||
*.retry
|
||||
.ansible/
|
||||
.vault-pass
|
||||
vault-pass.txt
|
||||
*.secret
|
||||
*.key
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
ansible.log
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Molecule
|
||||
.molecule/
|
||||
.cache/
|
||||
|
||||
# Terraform (if using)
|
||||
*.tfstate
|
||||
*.tfstate.backup
|
||||
.terraform/
|
||||
```
|
||||
|
||||
### 5. Setup Ansible Vault
|
||||
|
||||
If vault enabled:
|
||||
|
||||
```bash
|
||||
# Create vault password file (DO NOT COMMIT)
|
||||
echo "your-secure-password" > .vault-pass
|
||||
chmod 600 .vault-pass
|
||||
|
||||
# Create encrypted vault files for each environment
|
||||
ansible-vault create inventory/production/group_vars/all/vault.yml
|
||||
ansible-vault create inventory/staging/group_vars/all/vault.yml
|
||||
ansible-vault create inventory/development/group_vars/all/vault.yml
|
||||
```
|
||||
|
||||
**Vault file template**:
|
||||
```yaml
|
||||
---
|
||||
# Encrypted secrets for [environment]
|
||||
|
||||
# Database credentials
|
||||
vault_db_root_password: "changeme"
|
||||
vault_db_user_password: "changeme"
|
||||
|
||||
# API keys
|
||||
vault_api_key: "changeme"
|
||||
|
||||
# SSH keys
|
||||
vault_deploy_key: |
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
...
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
|
||||
# SSL certificates
|
||||
vault_ssl_key: |
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
...
|
||||
-----END PRIVATE KEY-----
|
||||
```
|
||||
|
||||
### 6. Create requirements.yml
|
||||
|
||||
Define Galaxy role dependencies:
|
||||
|
||||
```yaml
|
||||
---
|
||||
# Ansible Galaxy roles
|
||||
|
||||
roles:
|
||||
# Community roles
|
||||
- name: geerlingguy.docker
|
||||
version: "6.1.0"
|
||||
|
||||
- name: geerlingguy.nginx
|
||||
version: "3.1.4"
|
||||
|
||||
collections:
|
||||
# Community collections
|
||||
- name: community.general
|
||||
version: ">=7.0.0"
|
||||
|
||||
- name: ansible.posix
|
||||
version: ">=1.5.0"
|
||||
|
||||
- name: community.postgresql
|
||||
version: ">=3.0.0"
|
||||
```
|
||||
|
||||
**Install dependencies**:
|
||||
```bash
|
||||
ansible-galaxy install -r requirements.yml
|
||||
```
|
||||
|
||||
### 7. Create Example Inventory
|
||||
|
||||
**inventory/development/hosts.yml**:
|
||||
```yaml
|
||||
---
|
||||
all:
|
||||
children:
|
||||
webservers:
|
||||
hosts:
|
||||
web01:
|
||||
ansible_host: 192.168.1.10
|
||||
ansible_user: ansible
|
||||
web02:
|
||||
ansible_host: 192.168.1.11
|
||||
ansible_user: ansible
|
||||
vars:
|
||||
nginx_port: 80
|
||||
app_environment: development
|
||||
|
||||
databases:
|
||||
hosts:
|
||||
db01:
|
||||
ansible_host: 192.168.1.20
|
||||
ansible_user: ansible
|
||||
vars:
|
||||
postgresql_version: "15"
|
||||
db_environment: development
|
||||
|
||||
loadbalancers:
|
||||
hosts:
|
||||
lb01:
|
||||
ansible_host: 192.168.1.30
|
||||
ansible_user: ansible
|
||||
|
||||
vars:
|
||||
ansible_python_interpreter: /usr/bin/python3
|
||||
ansible_become: yes
|
||||
```
|
||||
|
||||
### 8. Create Master Playbook
|
||||
|
||||
**playbooks/site.yml**:
|
||||
```yaml
|
||||
---
|
||||
- name: Configure all servers
|
||||
hosts: all
|
||||
gather_facts: yes
|
||||
become: yes
|
||||
|
||||
pre_tasks:
|
||||
- name: Update apt cache (Debian/Ubuntu)
|
||||
ansible.builtin.apt:
|
||||
update_cache: yes
|
||||
cache_valid_time: 3600
|
||||
when: ansible_os_family == "Debian"
|
||||
tags: always
|
||||
|
||||
- name: Display environment
|
||||
ansible.builtin.debug:
|
||||
msg: "Configuring {{ inventory_hostname }} in {{ app_environment | default('unknown') }} environment"
|
||||
tags: always
|
||||
|
||||
roles:
|
||||
- role: common
|
||||
tags: common
|
||||
|
||||
- name: Configure web servers
|
||||
hosts: webservers
|
||||
become: yes
|
||||
|
||||
roles:
|
||||
- role: nginx
|
||||
tags: nginx
|
||||
- role: application
|
||||
tags: app
|
||||
|
||||
- name: Configure database servers
|
||||
hosts: databases
|
||||
become: yes
|
||||
|
||||
roles:
|
||||
- role: postgresql
|
||||
tags: database
|
||||
|
||||
- name: Configure load balancers
|
||||
hosts: loadbalancers
|
||||
become: yes
|
||||
|
||||
roles:
|
||||
- role: haproxy
|
||||
tags: loadbalancer
|
||||
```
|
||||
|
||||
### 9. Create Example Role
|
||||
|
||||
Create a common role:
|
||||
|
||||
```bash
|
||||
ansible-galaxy role init roles/common
|
||||
```
|
||||
|
||||
**roles/common/tasks/main.yml**:
|
||||
```yaml
|
||||
---
|
||||
- name: Ensure common packages are installed
|
||||
ansible.builtin.package:
|
||||
name:
|
||||
- curl
|
||||
- wget
|
||||
- git
|
||||
- vim
|
||||
- htop
|
||||
- net-tools
|
||||
state: present
|
||||
tags: packages
|
||||
|
||||
- name: Configure timezone
|
||||
community.general.timezone:
|
||||
name: "{{ timezone | default('UTC') }}"
|
||||
tags: timezone
|
||||
|
||||
- name: Configure NTP
|
||||
ansible.builtin.include_tasks: ntp.yml
|
||||
when: configure_ntp | default(true)
|
||||
tags: ntp
|
||||
|
||||
- name: Harden SSH configuration
|
||||
ansible.builtin.include_tasks: ssh.yml
|
||||
tags: ssh
|
||||
|
||||
- name: Configure firewall
|
||||
ansible.builtin.include_tasks: firewall.yml
|
||||
when: configure_firewall | default(true)
|
||||
tags: firewall
|
||||
```
|
||||
|
||||
### 10. Setup Molecule Testing (Optional)
|
||||
|
||||
If testing enabled:
|
||||
|
||||
```bash
|
||||
# Install molecule
|
||||
pip install molecule molecule-plugins[docker] ansible-lint
|
||||
|
||||
# Initialize molecule for a role
|
||||
cd roles/common
|
||||
molecule init scenario default --driver-name docker
|
||||
```
|
||||
|
||||
**molecule/default/molecule.yml**:
|
||||
```yaml
|
||||
---
|
||||
dependency:
|
||||
name: galaxy
|
||||
options:
|
||||
requirements-file: requirements.yml
|
||||
|
||||
driver:
|
||||
name: docker
|
||||
|
||||
platforms:
|
||||
- name: ubuntu-20.04
|
||||
image: geerlingguy/docker-ubuntu2004-ansible
|
||||
privileged: true
|
||||
pre_build_image: true
|
||||
|
||||
- name: ubuntu-22.04
|
||||
image: geerlingguy/docker-ubuntu2204-ansible
|
||||
privileged: true
|
||||
pre_build_image: true
|
||||
|
||||
provisioner:
|
||||
name: ansible
|
||||
config_options:
|
||||
defaults:
|
||||
callbacks_enabled: profile_tasks
|
||||
inventory:
|
||||
host_vars:
|
||||
ubuntu-20.04:
|
||||
ansible_python_interpreter: /usr/bin/python3
|
||||
ubuntu-22.04:
|
||||
ansible_python_interpreter: /usr/bin/python3
|
||||
|
||||
verifier:
|
||||
name: ansible
|
||||
|
||||
lint: |
|
||||
set -e
|
||||
ansible-lint
|
||||
yamllint .
|
||||
```
|
||||
|
||||
### 11. Create ansible-lint Configuration
|
||||
|
||||
**.ansible-lint**:
|
||||
```yaml
|
||||
---
|
||||
# Ansible-lint configuration
|
||||
|
||||
# Exclude paths
|
||||
exclude_paths:
|
||||
- .github/
|
||||
- molecule/
|
||||
- .molecule/
|
||||
- venv/
|
||||
|
||||
# Enable specific rules
|
||||
enable_list:
|
||||
- yaml
|
||||
- no-changed-when
|
||||
- no-handler
|
||||
|
||||
# Skip specific rules for entire project
|
||||
skip_list:
|
||||
- experimental
|
||||
- role-name # If using non-standard role names
|
||||
|
||||
# Profile to use (min, basic, moderate, safety, shared, production)
|
||||
profile: production
|
||||
|
||||
# Offline mode (no internet required)
|
||||
offline: false
|
||||
|
||||
# Use colors in output
|
||||
use_color: true
|
||||
```
|
||||
|
||||
### 12. Create README.md
|
||||
|
||||
**README.md**:
|
||||
```markdown
|
||||
# Project Name
|
||||
|
||||
Brief description of the Ansible project and its purpose.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Ansible 2.9 or higher
|
||||
- Python 3.8 or higher
|
||||
- Target systems: Ubuntu 20.04+, Debian 11+
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `inventory/` - Inventory files per environment
|
||||
- `roles/` - Custom Ansible roles
|
||||
- `playbooks/` - Ansible playbooks
|
||||
- `group_vars/` - Group variables
|
||||
- `host_vars/` - Host-specific variables
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Install Dependencies
|
||||
|
||||
\`\`\`bash
|
||||
# Install Python dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Install Ansible Galaxy roles
|
||||
ansible-galaxy install -r requirements.yml
|
||||
\`\`\`
|
||||
|
||||
### 2. Configure Vault
|
||||
|
||||
\`\`\`bash
|
||||
# Create vault password file (DO NOT COMMIT)
|
||||
echo "your-secure-password" > .vault-pass
|
||||
chmod 600 .vault-pass
|
||||
|
||||
# Create vault files
|
||||
ansible-vault create inventory/development/group_vars/all/vault.yml
|
||||
\`\`\`
|
||||
|
||||
### 3. Test Connection
|
||||
|
||||
\`\`\`bash
|
||||
# Ping all hosts
|
||||
ansible all -i inventory/development -m ping
|
||||
|
||||
# Gather facts
|
||||
ansible all -i inventory/development -m setup
|
||||
\`\`\`
|
||||
|
||||
### 4. Run Playbooks
|
||||
|
||||
\`\`\`bash
|
||||
# Dry run (check mode)
|
||||
ansible-playbook playbooks/site.yml -i inventory/development --check
|
||||
|
||||
# Run playbook
|
||||
ansible-playbook playbooks/site.yml -i inventory/development
|
||||
|
||||
# Run specific tags
|
||||
ansible-playbook playbooks/site.yml -i inventory/development --tags "common,nginx"
|
||||
|
||||
# Limit to specific hosts
|
||||
ansible-playbook playbooks/site.yml -i inventory/development --limit "webservers"
|
||||
\`\`\`
|
||||
|
||||
## Environments
|
||||
|
||||
- **development**: `inventory/development/`
|
||||
- **staging**: `inventory/staging/`
|
||||
- **production**: `inventory/production/`
|
||||
|
||||
Switch environments by changing the inventory path:
|
||||
\`\`\`bash
|
||||
ansible-playbook playbooks/site.yml -i inventory/production
|
||||
\`\`\`
|
||||
|
||||
## Ansible Vault
|
||||
|
||||
### Encrypt/Decrypt Files
|
||||
|
||||
\`\`\`bash
|
||||
# Encrypt a file
|
||||
ansible-vault encrypt inventory/production/group_vars/all/vault.yml
|
||||
|
||||
# Decrypt a file (temporary)
|
||||
ansible-vault decrypt inventory/production/group_vars/all/vault.yml
|
||||
|
||||
# Edit encrypted file
|
||||
ansible-vault edit inventory/production/group_vars/all/vault.yml
|
||||
|
||||
# View encrypted file
|
||||
ansible-vault view inventory/production/group_vars/all/vault.yml
|
||||
|
||||
# Change vault password
|
||||
ansible-vault rekey inventory/production/group_vars/all/vault.yml
|
||||
\`\`\`
|
||||
|
||||
### Encrypt Variables
|
||||
|
||||
\`\`\`bash
|
||||
# Encrypt a string
|
||||
ansible-vault encrypt_string 'secret_password' --name 'db_password'
|
||||
\`\`\`
|
||||
|
||||
## Testing
|
||||
|
||||
### Syntax Check
|
||||
|
||||
\`\`\`bash
|
||||
ansible-playbook playbooks/site.yml --syntax-check
|
||||
\`\`\`
|
||||
|
||||
### Lint
|
||||
|
||||
\`\`\`bash
|
||||
ansible-lint roles/
|
||||
ansible-lint playbooks/
|
||||
\`\`\`
|
||||
|
||||
### Molecule (Role Testing)
|
||||
|
||||
\`\`\`bash
|
||||
cd roles/common
|
||||
|
||||
# Run all tests
|
||||
molecule test
|
||||
|
||||
# Create test instance
|
||||
molecule create
|
||||
|
||||
# Run playbook
|
||||
molecule converge
|
||||
|
||||
# Verify tests
|
||||
molecule verify
|
||||
|
||||
# Destroy test instance
|
||||
molecule destroy
|
||||
\`\`\`
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. Create/modify roles in `roles/`
|
||||
2. Update playbooks in `playbooks/`
|
||||
3. Test with ansible-lint
|
||||
4. Run in check mode first
|
||||
5. Test in development environment
|
||||
6. Review and approve changes
|
||||
7. Deploy to staging
|
||||
8. Deploy to production
|
||||
|
||||
## Common Tasks
|
||||
|
||||
### Add New Server
|
||||
|
||||
1. Add host to inventory: `inventory/<env>/hosts.yml`
|
||||
2. Configure host variables if needed: `host_vars/<hostname>.yml`
|
||||
3. Run provisioning: `ansible-playbook playbooks/provision.yml -i inventory/<env> --limit <hostname>`
|
||||
|
||||
### Add New Role
|
||||
|
||||
\`\`\`bash
|
||||
# Create role structure
|
||||
ansible-galaxy role init roles/<role-name>
|
||||
|
||||
# Add role to requirements.yml if third-party
|
||||
# Include role in appropriate playbook
|
||||
\`\`\`
|
||||
|
||||
### Deploy Application
|
||||
|
||||
\`\`\`bash
|
||||
ansible-playbook playbooks/deploy.yml -i inventory/<env> \
|
||||
--extra-vars "app_version=v1.2.3"
|
||||
\`\`\`
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Connection Issues
|
||||
|
||||
\`\`\`bash
|
||||
# Test SSH connectivity
|
||||
ansible all -i inventory/development -m ping -vvv
|
||||
|
||||
# Check inventory
|
||||
ansible-inventory -i inventory/development --list
|
||||
ansible-inventory -i inventory/development --graph
|
||||
\`\`\`
|
||||
|
||||
### Playbook Failures
|
||||
|
||||
\`\`\`bash
|
||||
# Run with increased verbosity
|
||||
ansible-playbook playbooks/site.yml -vvv
|
||||
|
||||
# Check specific host
|
||||
ansible-playbook playbooks/site.yml --limit <hostname> -vv
|
||||
\`\`\`
|
||||
|
||||
### Vault Issues
|
||||
|
||||
\`\`\`bash
|
||||
# Verify vault password
|
||||
ansible-vault view inventory/development/group_vars/all/vault.yml
|
||||
|
||||
# Check vault password file permissions
|
||||
ls -la .vault-pass # Should be 600
|
||||
\`\`\`
|
||||
|
||||
## Contributing
|
||||
|
||||
1. Follow Ansible best practices
|
||||
2. Test changes with ansible-lint
|
||||
3. Test in development environment first
|
||||
4. Document changes in playbook/role README
|
||||
5. Use meaningful commit messages
|
||||
|
||||
## License
|
||||
|
||||
[Your License]
|
||||
|
||||
## Author
|
||||
|
||||
[Your Name/Team]
|
||||
```
|
||||
|
||||
### 13. Verify Project Setup
|
||||
|
||||
Run validation commands:
|
||||
|
||||
```bash
|
||||
# Check ansible.cfg syntax
|
||||
ansible-config dump
|
||||
|
||||
# Verify inventory structure
|
||||
ansible-inventory -i inventory/development --graph
|
||||
ansible-inventory -i inventory/development --list
|
||||
|
||||
# Test connection to hosts
|
||||
ansible all -i inventory/development -m ping
|
||||
|
||||
# Syntax check playbooks
|
||||
ansible-playbook playbooks/site.yml --syntax-check
|
||||
|
||||
# Lint the project
|
||||
ansible-lint roles/
|
||||
ansible-lint playbooks/
|
||||
|
||||
# Dry run
|
||||
ansible-playbook playbooks/site.yml -i inventory/development --check
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
### Project Initialization Summary
|
||||
|
||||
**Project**: [project-name]
|
||||
**Location**: [path]
|
||||
**Environments**: [dev, staging, production]
|
||||
**Initial Roles**: [list of roles created]
|
||||
|
||||
**Directory Structure Created**:
|
||||
```
|
||||
✓ ansible.cfg - Ansible configuration
|
||||
✓ inventory/ - Multi-environment inventory
|
||||
✓ roles/ - Custom roles
|
||||
✓ playbooks/ - Master and environment playbooks
|
||||
✓ group_vars/ - Global variables
|
||||
✓ vault setup - Encrypted secrets per environment
|
||||
✓ requirements.yml - Galaxy dependencies
|
||||
✓ .gitignore - Git exclusions
|
||||
✓ README.md - Project documentation
|
||||
✓ .ansible-lint - Lint configuration
|
||||
✓ molecule/ - Testing framework (optional)
|
||||
```
|
||||
|
||||
### Next Steps
|
||||
|
||||
**1. Configure Inventory**:
|
||||
```bash
|
||||
# Edit inventory file
|
||||
vi inventory/development/hosts.yml
|
||||
|
||||
# Add your hosts and variables
|
||||
```
|
||||
|
||||
**2. Setup Vault**:
|
||||
```bash
|
||||
# Create vault password
|
||||
echo "your-password" > .vault-pass
|
||||
chmod 600 .vault-pass
|
||||
|
||||
# Create encrypted secrets
|
||||
ansible-vault create inventory/development/group_vars/all/vault.yml
|
||||
```
|
||||
|
||||
**3. Install Dependencies**:
|
||||
```bash
|
||||
ansible-galaxy install -r requirements.yml
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
**4. Test Connection**:
|
||||
```bash
|
||||
ansible all -i inventory/development -m ping
|
||||
```
|
||||
|
||||
**5. Develop Roles**:
|
||||
```bash
|
||||
# Create new role
|
||||
ansible-galaxy role init roles/myapp
|
||||
|
||||
# Edit role tasks
|
||||
vi roles/myapp/tasks/main.yml
|
||||
```
|
||||
|
||||
**6. Run Playbooks**:
|
||||
```bash
|
||||
# Check mode first
|
||||
ansible-playbook playbooks/site.yml -i inventory/development --check
|
||||
|
||||
# Execute
|
||||
ansible-playbook playbooks/site.yml -i inventory/development
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
**Security**:
|
||||
- Never commit `.vault-pass` or unencrypted secrets
|
||||
- Use Ansible Vault for all sensitive data
|
||||
- Separate vault files per environment
|
||||
- Rotate vault passwords regularly
|
||||
- Use SSH keys, not passwords
|
||||
|
||||
**Organization**:
|
||||
- One role per purpose (single responsibility)
|
||||
- Keep playbooks simple, logic in roles
|
||||
- Use tags for selective execution
|
||||
- Group related tasks in separate files
|
||||
- Follow ansible-galaxy role structure
|
||||
|
||||
**Testing**:
|
||||
- Always run in check mode first (`--check`)
|
||||
- Test in development before production
|
||||
- Use ansible-lint for code quality
|
||||
- Implement Molecule tests for roles
|
||||
- Use CI/CD for automated testing
|
||||
|
||||
**Version Control**:
|
||||
- Commit early and often
|
||||
- Use meaningful commit messages
|
||||
- Tag releases (v1.0.0, v1.1.0, etc.)
|
||||
- Branch for features/fixes
|
||||
- Review changes before production
|
||||
|
||||
**Documentation**:
|
||||
- README in every role
|
||||
- Document all variables
|
||||
- Include example playbooks
|
||||
- Keep documentation up to date
|
||||
- Explain non-obvious decisions
|
||||
577
commands/create-jinja2-template.md
Normal file
577
commands/create-jinja2-template.md
Normal file
@@ -0,0 +1,577 @@
|
||||
---
|
||||
description: Create Jinja2 templates for Ansible
|
||||
argument-hint: Optional template requirements
|
||||
---
|
||||
|
||||
# Jinja2 Template Creation
|
||||
|
||||
You are creating Jinja2 templates for Ansible using the jinja2-developer agent, which coordinates with domain specialists for accurate technical content.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Identify Template Requirements
|
||||
|
||||
Determine what template is needed:
|
||||
- **Configuration files**: Application configs, server configs
|
||||
- **Scripts**: Shell scripts, service files
|
||||
- **Web content**: HTML, nginx configs, Apache configs
|
||||
- **Network configs**: FRR, netplan, interfaces
|
||||
- **Database configs**: PostgreSQL, MySQL, MongoDB
|
||||
- **System files**: /etc files, systemd units
|
||||
|
||||
### 2. Gather Template Information
|
||||
|
||||
If not specified, ask for:
|
||||
- **Template purpose**:
|
||||
- What file is being generated
|
||||
- Target application or service
|
||||
- Configuration goals
|
||||
- **Domain/technology**:
|
||||
- Web server (Nginx, Apache, Caddy)
|
||||
- Database (PostgreSQL, MySQL, Redis)
|
||||
- Network (FRR, BGP, OSPF, interfaces)
|
||||
- Application (custom app config)
|
||||
- System (systemd, cron, logrotate)
|
||||
- **Variables needed**:
|
||||
- Required variables (no defaults)
|
||||
- Optional variables (with defaults)
|
||||
- Variable types and validation
|
||||
- **Target platform**:
|
||||
- Operating system
|
||||
- Software versions
|
||||
- Environment (dev/staging/production)
|
||||
- **Domain specialist needed**:
|
||||
- Which specialist agent to consult
|
||||
- What expertise is required
|
||||
|
||||
### 3. Identify Domain Expert
|
||||
|
||||
**CRITICAL**: Before developing templates with technical content, identify specialist:
|
||||
|
||||
**Network configurations**:
|
||||
- FRR routing configs → `frr-config-generator`
|
||||
- Netplan configs → `netplan-config-generator`
|
||||
- Network interfaces → `interfaces-config-generator`
|
||||
|
||||
**Web servers**:
|
||||
- Nginx configs → Web server specialist
|
||||
- Apache configs → Web server specialist
|
||||
- HAProxy configs → Load balancer specialist
|
||||
|
||||
**Databases**:
|
||||
- PostgreSQL configs → Database specialist
|
||||
- MySQL configs → Database specialist
|
||||
- MongoDB configs → Database specialist
|
||||
|
||||
**Applications**:
|
||||
- Custom app configs → Application specialist
|
||||
- Kubernetes manifests → K8s specialist
|
||||
|
||||
**System**:
|
||||
- Systemd units → System specialist
|
||||
- Security configs → Security specialist
|
||||
|
||||
### 4. Consult Domain Specialist
|
||||
|
||||
**Ask user which specialist to consult**, then:
|
||||
|
||||
Launch appropriate specialist agent:
|
||||
```
|
||||
"Generate [technology] configuration for [purpose].
|
||||
Requirements:
|
||||
- [List specific requirements]
|
||||
- Target: [platform/version]
|
||||
- Environment: [dev/staging/prod]
|
||||
- Best practices for [specific concerns]"
|
||||
```
|
||||
|
||||
### 5. Create Template
|
||||
|
||||
Launch **jinja2-developer** with specialist guidance:
|
||||
```
|
||||
"Create Jinja2 template for [file/purpose].
|
||||
Technology: [web server/database/network/etc.]
|
||||
Specialist consulted: [agent-name]
|
||||
Specialist recommendations: [guidance from specialist]
|
||||
|
||||
Variables:
|
||||
- Required: [list]
|
||||
- Optional: [list with defaults]
|
||||
|
||||
Template should:
|
||||
- Include ansible_managed header
|
||||
- Incorporate specialist's configuration recommendations
|
||||
- Use proper Jinja2 syntax
|
||||
- Validate inputs where possible
|
||||
- Support different environments
|
||||
- Include helpful comments
|
||||
- Document all variables"
|
||||
```
|
||||
|
||||
### 6. Review Template
|
||||
|
||||
Check generated template for:
|
||||
- **Syntax**: Valid Jinja2 syntax
|
||||
- **Variables**: All variables defined and used correctly
|
||||
- **Defaults**: Sensible default values with `| default()`
|
||||
- **Validation**: Input checking where possible
|
||||
- **Comments**: Clear documentation
|
||||
- **ansible_managed**: Included in header
|
||||
- **Specialist guidance**: Properly incorporated
|
||||
- **Platform-specific**: OS/version conditionals if needed
|
||||
|
||||
### 7. Create Example Task
|
||||
|
||||
Generate example Ansible task to use the template:
|
||||
|
||||
```yaml
|
||||
- name: Template [file description]
|
||||
ansible.builtin.template:
|
||||
src: [template-name].j2
|
||||
dest: /path/to/destination
|
||||
owner: [user]
|
||||
group: [group]
|
||||
mode: '0644'
|
||||
validate: '[validation-command %s]' # If available
|
||||
backup: yes
|
||||
notify: [Handler name]
|
||||
tags: config
|
||||
```
|
||||
|
||||
### 8. Test Template
|
||||
|
||||
Validate template works:
|
||||
|
||||
```bash
|
||||
# Test template rendering
|
||||
ansible-playbook test-template.yml -i localhost, --connection=local
|
||||
|
||||
# Check rendered output
|
||||
cat /tmp/rendered-template
|
||||
|
||||
# Validate syntax (if validator available)
|
||||
nginx -t -c /tmp/rendered-template # For nginx
|
||||
postgresql --check /tmp/rendered-template # For PostgreSQL
|
||||
```
|
||||
|
||||
## Template Development Patterns
|
||||
|
||||
### Basic Configuration Template
|
||||
|
||||
**Example: Application Config**
|
||||
|
||||
```jinja2
|
||||
{#
|
||||
Template: app_config.ini.j2
|
||||
Purpose: Application configuration file
|
||||
Specialist: None (simple key-value config)
|
||||
|
||||
Required Variables:
|
||||
app_name: Application name
|
||||
app_port: Port to listen on
|
||||
|
||||
Optional Variables:
|
||||
app_debug: Enable debug mode (default: false)
|
||||
app_log_level: Logging level (default: info)
|
||||
app_workers: Number of workers (default: 4)
|
||||
#}
|
||||
|
||||
# {{ ansible_managed }}
|
||||
# Application Configuration
|
||||
|
||||
[general]
|
||||
name = {{ app_name }}
|
||||
port = {{ app_port }}
|
||||
environment = {{ app_environment | default('production') }}
|
||||
|
||||
{% if app_debug | default(false) %}
|
||||
debug = true
|
||||
log_level = debug
|
||||
{% else %}
|
||||
debug = false
|
||||
log_level = {{ app_log_level | default('info') }}
|
||||
{% endif %}
|
||||
|
||||
[performance]
|
||||
workers = {{ app_workers | default(4) }}
|
||||
timeout = {{ app_timeout | default(30) }}
|
||||
keepalive = {{ app_keepalive | default(5) }}
|
||||
|
||||
[database]
|
||||
host = {{ db_host }}
|
||||
port = {{ db_port | default(5432) }}
|
||||
name = {{ db_name }}
|
||||
user = {{ db_user }}
|
||||
{% if db_ssl_enabled | default(true) %}
|
||||
ssl_mode = require
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### Network Configuration Template
|
||||
|
||||
**Example: FRR BGP (with specialist guidance)**
|
||||
|
||||
```jinja2
|
||||
{#
|
||||
Template: frr_bgp.conf.j2
|
||||
Purpose: FRR BGP routing configuration
|
||||
Specialist: frr-config-generator (consulted for BGP best practices)
|
||||
|
||||
Required Variables:
|
||||
bgp_local_asn: Local AS number
|
||||
bgp_router_id: BGP router ID
|
||||
bgp_peer_ip: Peer IP address
|
||||
bgp_peer_asn: Peer AS number
|
||||
|
||||
Optional Variables:
|
||||
bgp_peer_description: Peer description (default: 'BGP Peer')
|
||||
bgp_peer_password: Peer authentication password
|
||||
bgp_network: Network to advertise
|
||||
bgp_max_prefix: Maximum prefixes (default: 1000)
|
||||
#}
|
||||
|
||||
# {{ ansible_managed }}
|
||||
# FRR BGP Configuration
|
||||
# Specialist guidance: frr-config-generator
|
||||
|
||||
router bgp {{ bgp_local_asn }}
|
||||
bgp router-id {{ bgp_router_id }}
|
||||
bgp log-neighbor-changes
|
||||
no bgp default ipv4-unicast
|
||||
|
||||
{# Peer configuration from specialist recommendations #}
|
||||
neighbor {{ bgp_peer_ip }} remote-as {{ bgp_peer_asn }}
|
||||
neighbor {{ bgp_peer_ip }} description {{ bgp_peer_description | default('BGP Peer') }}
|
||||
|
||||
{% if bgp_peer_password is defined %}
|
||||
neighbor {{ bgp_peer_ip }} password {{ bgp_peer_password }}
|
||||
{% endif %}
|
||||
|
||||
{# Address family configuration #}
|
||||
address-family ipv4 unicast
|
||||
{% if bgp_network is defined %}
|
||||
network {{ bgp_network }}
|
||||
{% endif %}
|
||||
|
||||
neighbor {{ bgp_peer_ip }} activate
|
||||
neighbor {{ bgp_peer_ip }} prefix-list {{ bgp_prefix_list_in | default('PL-IN') }} in
|
||||
neighbor {{ bgp_peer_ip }} prefix-list {{ bgp_prefix_list_out | default('PL-OUT') }} out
|
||||
neighbor {{ bgp_peer_ip }} maximum-prefix {{ bgp_max_prefix | default(1000) }} 80
|
||||
|
||||
{% if bgp_default_originate | default(false) %}
|
||||
neighbor {{ bgp_peer_ip }} default-originate
|
||||
{% endif %}
|
||||
exit-address-family
|
||||
!
|
||||
|
||||
{# Prefix lists for route filtering #}
|
||||
{% if bgp_allowed_prefixes is defined %}
|
||||
ip prefix-list {{ bgp_prefix_list_in | default('PL-IN') }} seq 5 deny 0.0.0.0/0 le 32
|
||||
{% for prefix in bgp_allowed_prefixes %}
|
||||
ip prefix-list {{ bgp_prefix_list_in | default('PL-IN') }} seq {{ loop.index * 10 + 10 }} permit {{ prefix }}
|
||||
{% endfor %}
|
||||
!
|
||||
{% endif %}
|
||||
|
||||
{% if bgp_advertised_prefixes is defined %}
|
||||
{% for prefix in bgp_advertised_prefixes %}
|
||||
ip prefix-list {{ bgp_prefix_list_out | default('PL-OUT') }} seq {{ loop.index * 10 }} permit {{ prefix }}
|
||||
{% endfor %}
|
||||
ip prefix-list {{ bgp_prefix_list_out | default('PL-OUT') }} seq 1000 deny 0.0.0.0/0 le 32
|
||||
!
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### Web Server Template
|
||||
|
||||
**Example: Nginx Virtual Host**
|
||||
|
||||
```jinja2
|
||||
{#
|
||||
Template: nginx_vhost.conf.j2
|
||||
Purpose: Nginx virtual host configuration
|
||||
Specialist: Web server specialist (for SSL and security hardening)
|
||||
|
||||
Required Variables:
|
||||
vhost_domain: Domain name
|
||||
vhost_root: Document root path
|
||||
|
||||
Optional Variables:
|
||||
vhost_port: HTTP port (default: 80)
|
||||
vhost_ssl: Enable SSL (default: false)
|
||||
vhost_ssl_cert: SSL certificate path
|
||||
vhost_ssl_key: SSL key path
|
||||
vhost_locations: Custom location blocks
|
||||
#}
|
||||
|
||||
# {{ ansible_managed }}
|
||||
# Nginx Virtual Host: {{ vhost_domain }}
|
||||
|
||||
server {
|
||||
listen {{ vhost_port | default(80) }};
|
||||
server_name {{ vhost_domain }} {% if vhost_aliases is defined %}{{ vhost_aliases | join(' ') }}{% endif %};
|
||||
|
||||
{% if vhost_ssl | default(false) %}
|
||||
# SSL Configuration (from specialist recommendations)
|
||||
listen 443 ssl http2;
|
||||
ssl_certificate {{ vhost_ssl_cert }};
|
||||
ssl_certificate_key {{ vhost_ssl_key }};
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
ssl_session_timeout 10m;
|
||||
|
||||
# Security headers
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
{% endif %}
|
||||
|
||||
root {{ vhost_root }};
|
||||
index index.html index.htm {% if vhost_php | default(false) %}index.php{% endif %};
|
||||
|
||||
# Logging
|
||||
access_log /var/log/nginx/{{ vhost_domain }}_access.log;
|
||||
error_log /var/log/nginx/{{ vhost_domain }}_error.log;
|
||||
|
||||
# Default location
|
||||
location / {
|
||||
try_files $uri $uri/ {% if vhost_php | default(false) %}=404{% else %}/index.html{% endif %};
|
||||
}
|
||||
|
||||
{% if vhost_php | default(false) %}
|
||||
# PHP-FPM configuration
|
||||
location ~ \.php$ {
|
||||
try_files $uri =404;
|
||||
fastcgi_pass unix:/var/run/php/php-fpm.sock;
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
include fastcgi_params;
|
||||
}
|
||||
{% endif %}
|
||||
|
||||
{% if vhost_locations is defined %}
|
||||
# Custom locations
|
||||
{% for location in vhost_locations %}
|
||||
location {{ location.path }} {
|
||||
{% if location.proxy_pass is defined %}
|
||||
proxy_pass {{ location.proxy_pass }};
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
{% elif location.alias is defined %}
|
||||
alias {{ location.alias }};
|
||||
{% elif location.return is defined %}
|
||||
return {{ location.return }};
|
||||
{% endif %}
|
||||
|
||||
{% if location.auth_basic is defined %}
|
||||
auth_basic "{{ location.auth_basic }}";
|
||||
auth_basic_user_file {{ location.auth_basic_file }};
|
||||
{% endif %}
|
||||
}
|
||||
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
# Deny access to hidden files
|
||||
location ~ /\. {
|
||||
deny all;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
}
|
||||
|
||||
{% if vhost_ssl | default(false) and vhost_redirect_http | default(true) %}
|
||||
# Redirect HTTP to HTTPS
|
||||
server {
|
||||
listen {{ vhost_port | default(80) }};
|
||||
server_name {{ vhost_domain }};
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### Systemd Service Template
|
||||
|
||||
**Example: Systemd Unit File**
|
||||
|
||||
```jinja2
|
||||
{#
|
||||
Template: app_service.j2
|
||||
Purpose: Systemd service unit file
|
||||
Specialist: System specialist (for hardening and best practices)
|
||||
|
||||
Required Variables:
|
||||
service_name: Service name
|
||||
service_exec_start: Start command
|
||||
service_user: User to run as
|
||||
|
||||
Optional Variables:
|
||||
service_description: Service description
|
||||
service_working_directory: Working directory
|
||||
service_environment: Environment variables
|
||||
service_restart: Restart policy (default: on-failure)
|
||||
service_restart_sec: Restart delay (default: 10)
|
||||
#}
|
||||
|
||||
# {{ ansible_managed }}
|
||||
# Systemd Service: {{ service_name }}
|
||||
|
||||
[Unit]
|
||||
Description={{ service_description | default(service_name + ' Service') }}
|
||||
After=network.target {% if service_after is defined %}{{ service_after | join(' ') }}{% endif %}
|
||||
|
||||
{% if service_requires is defined %}
|
||||
Requires={{ service_requires | join(' ') }}
|
||||
{% endif %}
|
||||
|
||||
[Service]
|
||||
Type={{ service_type | default('simple') }}
|
||||
User={{ service_user }}
|
||||
{% if service_group is defined %}
|
||||
Group={{ service_group }}
|
||||
{% endif %}
|
||||
|
||||
{% if service_working_directory is defined %}
|
||||
WorkingDirectory={{ service_working_directory }}
|
||||
{% endif %}
|
||||
|
||||
{% if service_environment is defined %}
|
||||
{% for key, value in service_environment.items() %}
|
||||
Environment="{{ key }}={{ value }}"
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
ExecStart={{ service_exec_start }}
|
||||
{% if service_exec_reload is defined %}
|
||||
ExecReload={{ service_exec_reload }}
|
||||
{% endif %}
|
||||
|
||||
{% if service_exec_stop is defined %}
|
||||
ExecStop={{ service_exec_stop }}
|
||||
{% else %}
|
||||
KillMode={{ service_kill_mode | default('mixed') }}
|
||||
KillSignal={{ service_kill_signal | default('SIGTERM') }}
|
||||
{% endif %}
|
||||
|
||||
Restart={{ service_restart | default('on-failure') }}
|
||||
RestartSec={{ service_restart_sec | default(10) }}
|
||||
|
||||
# Security hardening (from specialist recommendations)
|
||||
{% if service_harden | default(true) %}
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem={{ service_protect_system | default('strict') }}
|
||||
ProtectHome={{ service_protect_home | default('true') }}
|
||||
ReadWritePaths={{ service_writable_paths | default(['/var/log/' + service_name, '/var/lib/' + service_name]) | join(' ') }}
|
||||
{% endif %}
|
||||
|
||||
# Resource limits
|
||||
{% if service_limit_nofile is defined %}
|
||||
LimitNOFILE={{ service_limit_nofile }}
|
||||
{% endif %}
|
||||
{% if service_limit_nproc is defined %}
|
||||
LimitNPROC={{ service_limit_nproc }}
|
||||
{% endif %}
|
||||
|
||||
# Logging
|
||||
StandardOutput={{ service_stdout | default('journal') }}
|
||||
StandardError={{ service_stderr | default('journal') }}
|
||||
SyslogIdentifier={{ service_name }}
|
||||
|
||||
[Install]
|
||||
WantedBy={{ service_wanted_by | default('multi-user.target') }}
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
### Template Delivery
|
||||
|
||||
**Template**: [template-name].j2
|
||||
**Purpose**: [description]
|
||||
**Specialist Consulted**: [agent-name or "None"]
|
||||
**Technology**: [web server/database/network/etc.]
|
||||
|
||||
**Variables**:
|
||||
|
||||
Required:
|
||||
- `variable_name`: Description, type, example
|
||||
- `another_var`: Description, type, example
|
||||
|
||||
Optional (with defaults):
|
||||
- `optional_var`: Description (default: value)
|
||||
- `another_optional`: Description (default: value)
|
||||
|
||||
**Example Ansible Task**:
|
||||
```yaml
|
||||
- name: Template [file description]
|
||||
ansible.builtin.template:
|
||||
src: [template-name].j2
|
||||
dest: /path/to/file
|
||||
owner: root
|
||||
group: root
|
||||
mode: '0644'
|
||||
validate: '[command %s]' # If applicable
|
||||
backup: yes
|
||||
notify: [Handler name]
|
||||
tags: config
|
||||
```
|
||||
|
||||
**Example Variables**:
|
||||
```yaml
|
||||
# In defaults/main.yml or group_vars
|
||||
variable_name: "value"
|
||||
another_var: 8080
|
||||
optional_var: "custom_value"
|
||||
```
|
||||
|
||||
**Testing**:
|
||||
```bash
|
||||
# Render template locally
|
||||
ansible-playbook test.yml -i localhost, --connection=local
|
||||
|
||||
# Validate rendered config
|
||||
[validation-command] /tmp/rendered-file
|
||||
|
||||
# Deploy to test environment
|
||||
ansible-playbook playbook.yml -i inventory/dev --check
|
||||
ansible-playbook playbook.yml -i inventory/dev
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
**Template Design**:
|
||||
- Always include `{{ ansible_managed }}` header
|
||||
- Use `| default()` for all optional variables
|
||||
- Add comments explaining non-obvious logic
|
||||
- Group related configuration sections
|
||||
- Use whitespace control (`{%-` and `-%}`) for clean output
|
||||
|
||||
**Variable Management**:
|
||||
- Namespace variables with role/template name
|
||||
- Document all variables in template header
|
||||
- Provide sensible defaults
|
||||
- Validate input where possible with `assert`
|
||||
|
||||
**Security**:
|
||||
- Never hardcode secrets in templates
|
||||
- Use Ansible Vault for sensitive variables
|
||||
- Set appropriate file permissions in task
|
||||
- Validate rendered configs before deploying
|
||||
|
||||
**Testing**:
|
||||
- Test rendering with example variables
|
||||
- Validate syntax of rendered output
|
||||
- Test in development before production
|
||||
- Use `validate` parameter when available
|
||||
|
||||
**Documentation**:
|
||||
- Document purpose in template header
|
||||
- List all required and optional variables
|
||||
- Include example values
|
||||
- Note specialist consultation if applicable
|
||||
- Explain complex logic with comments
|
||||
348
commands/develop-ansible.md
Normal file
348
commands/develop-ansible.md
Normal file
@@ -0,0 +1,348 @@
|
||||
---
|
||||
description: Develop Ansible roles and playbooks
|
||||
argument-hint: Optional role or playbook requirements
|
||||
---
|
||||
|
||||
# Ansible Development
|
||||
|
||||
You are developing Ansible automation (roles, playbooks, tasks, handlers) using the ansible-developer agent.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Identify Development Type
|
||||
|
||||
Determine what to develop:
|
||||
- **New role**: Complete role with tasks, handlers, defaults
|
||||
- **New playbook**: Standalone playbook or site playbook
|
||||
- **Task enhancement**: Add/modify tasks in existing role
|
||||
- **Handler creation**: Create service handlers
|
||||
- **Variable management**: Define defaults and vars
|
||||
- **Module development**: Custom Ansible modules
|
||||
|
||||
### 2. Gather Requirements
|
||||
|
||||
If not specified, ask for:
|
||||
|
||||
**For Roles**:
|
||||
- Role name and purpose
|
||||
- Target systems (OS, distributions)
|
||||
- Dependencies (packages, services, other roles)
|
||||
- Configuration files needed
|
||||
- Variables and their defaults
|
||||
- Handlers required (restarts, reloads)
|
||||
- Tags for selective execution
|
||||
|
||||
**For Playbooks**:
|
||||
- Playbook purpose (deploy, configure, maintain)
|
||||
- Target host groups
|
||||
- Roles to include
|
||||
- Pre-tasks and post-tasks
|
||||
- Variables needed
|
||||
- Execution order
|
||||
|
||||
**For Tasks**:
|
||||
- What the task should accomplish
|
||||
- Modules to use (package, service, template, etc.)
|
||||
- Idempotency requirements
|
||||
- Error handling needs
|
||||
- Conditionals (OS-specific, etc.)
|
||||
|
||||
### 3. Launch Development Agent
|
||||
|
||||
Launch **ansible-developer** with complete requirements:
|
||||
|
||||
```
|
||||
"Create Ansible role named [role-name] that [purpose].
|
||||
Target systems: [OS/distro]
|
||||
Requirements:
|
||||
- Install and configure [software]
|
||||
- Manage [service] with handlers
|
||||
- Template [config-files]
|
||||
- Variables: [list with defaults]
|
||||
- Support check mode
|
||||
- Include example playbook"
|
||||
```
|
||||
|
||||
### 4. Review Generated Code
|
||||
|
||||
Check the developed automation for:
|
||||
- **Idempotency**: All tasks can run multiple times safely
|
||||
- **Module usage**: Proper Ansible modules (not shell when module exists)
|
||||
- **Task naming**: Descriptive names starting with verbs
|
||||
- **Variables**: Proper namespacing (role_name_variable)
|
||||
- **Handlers**: Appropriate handler usage
|
||||
- **Error handling**: Block/rescue where needed
|
||||
- **Check mode**: Support for `--check` flag
|
||||
- **Tags**: Meaningful tags for selective execution
|
||||
|
||||
### 5. Test Development
|
||||
|
||||
Run validation commands:
|
||||
|
||||
```bash
|
||||
# Syntax check
|
||||
ansible-playbook playbooks/test.yml --syntax-check
|
||||
|
||||
# Lint check
|
||||
ansible-lint roles/[role-name]/
|
||||
|
||||
# Check mode (dry run)
|
||||
ansible-playbook playbooks/test.yml --check
|
||||
|
||||
# Run on test environment
|
||||
ansible-playbook playbooks/test.yml -i inventory/development
|
||||
|
||||
# Run specific tags
|
||||
ansible-playbook playbooks/test.yml --tags "install,config"
|
||||
|
||||
# Verbose output for debugging
|
||||
ansible-playbook playbooks/test.yml -vv
|
||||
```
|
||||
|
||||
### 6. Iterate if Needed
|
||||
|
||||
If issues found:
|
||||
- Launch ansible-code-reviewer to identify problems
|
||||
- Fix issues with ansible-developer
|
||||
- Re-test until all checks pass
|
||||
|
||||
## Common Development Patterns
|
||||
|
||||
### Creating a Role
|
||||
|
||||
**Example: Web Server Role**
|
||||
|
||||
```yaml
|
||||
# roles/nginx/tasks/main.yml
|
||||
---
|
||||
- name: Ensure Nginx is installed
|
||||
ansible.builtin.package:
|
||||
name: nginx
|
||||
state: present
|
||||
tags: install
|
||||
|
||||
- name: Ensure Nginx configuration directory exists
|
||||
ansible.builtin.file:
|
||||
path: /etc/nginx/sites-available
|
||||
state: directory
|
||||
owner: root
|
||||
group: root
|
||||
mode: '0755'
|
||||
tags: config
|
||||
|
||||
- name: Template Nginx main configuration
|
||||
ansible.builtin.template:
|
||||
src: nginx.conf.j2
|
||||
dest: /etc/nginx/nginx.conf
|
||||
owner: root
|
||||
group: root
|
||||
mode: '0644'
|
||||
validate: nginx -t -c %s
|
||||
backup: yes
|
||||
notify: Reload nginx
|
||||
tags: config
|
||||
|
||||
- name: Ensure Nginx is started and enabled
|
||||
ansible.builtin.service:
|
||||
name: nginx
|
||||
state: started
|
||||
enabled: yes
|
||||
tags: service
|
||||
```
|
||||
|
||||
**Handlers**:
|
||||
```yaml
|
||||
# roles/nginx/handlers/main.yml
|
||||
---
|
||||
- name: Reload nginx
|
||||
ansible.builtin.service:
|
||||
name: nginx
|
||||
state: reloaded
|
||||
|
||||
- name: Restart nginx
|
||||
ansible.builtin.service:
|
||||
name: nginx
|
||||
state: restarted
|
||||
```
|
||||
|
||||
**Defaults**:
|
||||
```yaml
|
||||
# roles/nginx/defaults/main.yml
|
||||
---
|
||||
nginx_worker_processes: auto
|
||||
nginx_worker_connections: 1024
|
||||
nginx_user: www-data
|
||||
nginx_keepalive_timeout: 65
|
||||
nginx_server_names_hash_bucket_size: 64
|
||||
```
|
||||
|
||||
### Creating a Playbook
|
||||
|
||||
**Example: Site Deployment Playbook**
|
||||
|
||||
```yaml
|
||||
---
|
||||
- name: Deploy web application
|
||||
hosts: webservers
|
||||
become: yes
|
||||
gather_facts: yes
|
||||
|
||||
vars:
|
||||
app_version: "1.0.0"
|
||||
deployment_user: deploy
|
||||
|
||||
pre_tasks:
|
||||
- name: Update package cache
|
||||
ansible.builtin.apt:
|
||||
update_cache: yes
|
||||
cache_valid_time: 3600
|
||||
when: ansible_os_family == "Debian"
|
||||
tags: always
|
||||
|
||||
- name: Verify deployment user exists
|
||||
ansible.builtin.user:
|
||||
name: "{{ deployment_user }}"
|
||||
state: present
|
||||
tags: always
|
||||
|
||||
roles:
|
||||
- role: common
|
||||
tags: common
|
||||
- role: nginx
|
||||
tags: nginx
|
||||
- role: application
|
||||
tags: app
|
||||
|
||||
tasks:
|
||||
- name: Deploy application version {{ app_version }}
|
||||
ansible.builtin.copy:
|
||||
src: "app-{{ app_version }}.tar.gz"
|
||||
dest: "/opt/app/"
|
||||
owner: "{{ deployment_user }}"
|
||||
group: "{{ deployment_user }}"
|
||||
mode: '0644'
|
||||
tags: deploy
|
||||
|
||||
- name: Extract application
|
||||
ansible.builtin.unarchive:
|
||||
src: "/opt/app/app-{{ app_version }}.tar.gz"
|
||||
dest: "/opt/app/"
|
||||
remote_src: yes
|
||||
owner: "{{ deployment_user }}"
|
||||
group: "{{ deployment_user }}"
|
||||
tags: deploy
|
||||
|
||||
post_tasks:
|
||||
- name: Verify application is accessible
|
||||
ansible.builtin.uri:
|
||||
url: "http://{{ ansible_default_ipv4.address }}/"
|
||||
status_code: 200
|
||||
tags: verify
|
||||
|
||||
- name: Log deployment
|
||||
ansible.builtin.lineinfile:
|
||||
path: /var/log/deployments.log
|
||||
line: "{{ ansible_date_time.iso8601 }} - Deployed {{ app_version }}"
|
||||
create: yes
|
||||
tags: always
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
### Development Summary
|
||||
|
||||
**Created**: [role-name / playbook-name]
|
||||
**Purpose**: [description]
|
||||
**Files Generated**:
|
||||
```
|
||||
✓ tasks/main.yml - Main task list
|
||||
✓ handlers/main.yml - Service handlers
|
||||
✓ defaults/main.yml - Default variables
|
||||
✓ templates/ - Configuration templates
|
||||
✓ README.md - Role documentation
|
||||
```
|
||||
|
||||
### Usage Instructions
|
||||
|
||||
**Install role**:
|
||||
```bash
|
||||
# If using Galaxy
|
||||
ansible-galaxy install [role-name]
|
||||
|
||||
# Local role (no action needed)
|
||||
```
|
||||
|
||||
**Run playbook**:
|
||||
```bash
|
||||
# Syntax check
|
||||
ansible-playbook playbook.yml --syntax-check
|
||||
|
||||
# Dry run
|
||||
ansible-playbook playbook.yml --check
|
||||
|
||||
# Execute
|
||||
ansible-playbook playbook.yml -i inventory/production
|
||||
|
||||
# Specific tags
|
||||
ansible-playbook playbook.yml --tags "install,config"
|
||||
|
||||
# Limit to hosts
|
||||
ansible-playbook playbook.yml --limit "web01,web02"
|
||||
```
|
||||
|
||||
### Testing Commands
|
||||
|
||||
```bash
|
||||
# Lint check
|
||||
ansible-lint roles/[role-name]/
|
||||
|
||||
# Test with Molecule
|
||||
cd roles/[role-name]
|
||||
molecule test
|
||||
|
||||
# Manual test
|
||||
ansible-playbook tests/test.yml -i tests/inventory
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
**Idempotency**:
|
||||
- Use proper Ansible modules (not shell/command when module exists)
|
||||
- Always set `changed_when` for command/shell tasks
|
||||
- Use state management (present/absent, started/stopped)
|
||||
|
||||
**Task Naming**:
|
||||
- Start with verb (Ensure, Configure, Install, Copy, etc.)
|
||||
- Be specific about what task does
|
||||
- Use sentence case consistently
|
||||
|
||||
**Variables**:
|
||||
- Namespace with role name: `nginx_port`, `app_user`
|
||||
- Provide sensible defaults in `defaults/main.yml`
|
||||
- Document all variables in README
|
||||
|
||||
**Error Handling**:
|
||||
- Use `failed_when` to define failure conditions
|
||||
- Use `block/rescue` for rollback capability
|
||||
- Validate before destructive operations
|
||||
|
||||
**Templates**:
|
||||
- Add `{{ ansible_managed }}` header
|
||||
- Use validate parameter when possible
|
||||
- Always backup with `backup: yes`
|
||||
|
||||
**Handlers**:
|
||||
- One handler per service action
|
||||
- Use notify instead of direct service restarts
|
||||
- Name handlers clearly (Restart nginx, Reload postgresql)
|
||||
|
||||
**Tags**:
|
||||
- Add meaningful tags to tasks
|
||||
- Use common tags (install, config, service)
|
||||
- Allow selective execution
|
||||
|
||||
**Testing**:
|
||||
- Always support check mode
|
||||
- Test on multiple OS if targeting multiple platforms
|
||||
- Use Molecule for automated testing
|
||||
- Include example playbook in role
|
||||
362
commands/review-ansible-code.md
Normal file
362
commands/review-ansible-code.md
Normal file
@@ -0,0 +1,362 @@
|
||||
---
|
||||
description: Review Ansible code for quality and best practices
|
||||
argument-hint: Optional code to review
|
||||
---
|
||||
|
||||
# Ansible Code Review
|
||||
|
||||
You are reviewing Ansible code for errors, best practices, idempotency, and maintainability using the ansible-code-reviewer agent.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Identify Review Scope
|
||||
|
||||
Determine what needs review:
|
||||
- **Single role**: Specific role directory
|
||||
- **Multiple roles**: All roles in project
|
||||
- **Playbook**: Playbook file(s)
|
||||
- **Tasks file**: Specific tasks/main.yml
|
||||
- **Entire project**: All Ansible code
|
||||
|
||||
### 2. Gather Code and Context
|
||||
|
||||
If not specified, ask for:
|
||||
- **Code location**:
|
||||
- File paths or directories
|
||||
- Or paste code directly
|
||||
- **Code type**:
|
||||
- Role, playbook, tasks, handlers
|
||||
- **Target environment**:
|
||||
- Development, staging, production
|
||||
- Criticality level
|
||||
- **Specific concerns**:
|
||||
- Idempotency issues
|
||||
- Performance problems
|
||||
- Module selection
|
||||
- Code organization
|
||||
- **Constraints**:
|
||||
- Required Ansible version
|
||||
- Target OS/distributions
|
||||
- Must-use modules
|
||||
|
||||
### 3. Pre-Review Analysis
|
||||
|
||||
Before launching agent, check:
|
||||
- Code is accessible (file paths exist)
|
||||
- Syntax is valid (won't fail parsing)
|
||||
- Complete context provided
|
||||
|
||||
Run basic checks:
|
||||
```bash
|
||||
# Syntax validation
|
||||
ansible-playbook playbook.yml --syntax-check
|
||||
|
||||
# Basic lint
|
||||
ansible-lint roles/ --parseable
|
||||
```
|
||||
|
||||
### 4. Launch Code Reviewer
|
||||
|
||||
Launch **ansible-code-reviewer** with:
|
||||
```
|
||||
"Review Ansible code at [location].
|
||||
Type: [role/playbook/tasks]
|
||||
Environment: [dev/staging/production]
|
||||
Focus areas: [concerns if any]
|
||||
|
||||
Check for:
|
||||
- Idempotency violations
|
||||
- Module selection issues
|
||||
- Task naming quality
|
||||
- Variable management
|
||||
- Handler usage
|
||||
- Error handling
|
||||
- Check mode support
|
||||
- Performance issues
|
||||
- Code organization"
|
||||
```
|
||||
|
||||
### 5. Analyze Review Findings
|
||||
|
||||
The agent will categorize issues by severity:
|
||||
|
||||
**Critical** (Block deployment):
|
||||
- Syntax errors preventing execution
|
||||
- Idempotency violations causing data loss
|
||||
- Destructive operations without safeguards
|
||||
- Tasks that always fail
|
||||
- Hardcoded credentials (security)
|
||||
|
||||
**High** (Fix before deployment):
|
||||
- Non-idempotent operations
|
||||
- Shell/command when module available
|
||||
- Missing validation on critical changes
|
||||
- No backup before destructive changes
|
||||
- Improper handler usage
|
||||
- Missing error handling
|
||||
|
||||
**Medium** (Address soon):
|
||||
- Suboptimal code organization
|
||||
- Poor task naming
|
||||
- Generic variable names
|
||||
- Missing documentation
|
||||
- Performance inefficiencies
|
||||
- Missing tags
|
||||
|
||||
**Low** (Best practice improvements):
|
||||
- Style inconsistencies
|
||||
- Could use better Ansible features
|
||||
- Documentation could be more detailed
|
||||
- Minor optimizations
|
||||
|
||||
### 6. Prioritize Remediation
|
||||
|
||||
Create action plan:
|
||||
|
||||
**Immediate** (Before any deployment):
|
||||
1. Fix all Critical issues
|
||||
2. Validate fixes with testing
|
||||
|
||||
**Short-term** (This sprint):
|
||||
1. Fix High priority issues
|
||||
2. Re-review after changes
|
||||
|
||||
**Medium-term** (Next sprint):
|
||||
1. Address Medium issues
|
||||
2. Improve documentation
|
||||
|
||||
**Long-term** (Backlog):
|
||||
1. Low priority improvements
|
||||
2. Refactoring for maintainability
|
||||
|
||||
## Review Categories
|
||||
|
||||
### Idempotency Check
|
||||
|
||||
Agent checks that tasks:
|
||||
- Use proper state management modules
|
||||
- Don't use shell/command without `creates`/`removes`
|
||||
- Have `changed_when` set appropriately
|
||||
- Can run multiple times safely
|
||||
- Don't have uncontrolled side effects
|
||||
|
||||
**Example Issues**:
|
||||
```yaml
|
||||
# BAD - Not idempotent
|
||||
- name: Install nginx
|
||||
ansible.builtin.shell: apt-get install -y nginx
|
||||
|
||||
# GOOD - Idempotent
|
||||
- name: Ensure nginx is installed
|
||||
ansible.builtin.package:
|
||||
name: nginx
|
||||
state: present
|
||||
```
|
||||
|
||||
### Module Selection
|
||||
|
||||
Agent verifies:
|
||||
- Dedicated modules used over shell/command
|
||||
- Correct module for each task
|
||||
- Module parameters used properly
|
||||
- No deprecated modules
|
||||
|
||||
**Example Issues**:
|
||||
```yaml
|
||||
# BAD - Shell for directory creation
|
||||
- ansible.builtin.shell: mkdir -p /var/app
|
||||
|
||||
# GOOD - File module
|
||||
- ansible.builtin.file:
|
||||
path: /var/app
|
||||
state: directory
|
||||
```
|
||||
|
||||
### Task Naming
|
||||
|
||||
Agent checks:
|
||||
- Names start with verbs
|
||||
- Names are descriptive
|
||||
- Consistent sentence case
|
||||
- No generic names
|
||||
|
||||
**Example Issues**:
|
||||
```yaml
|
||||
# BAD
|
||||
- name: nginx
|
||||
- name: task1
|
||||
- name: copy file
|
||||
|
||||
# GOOD
|
||||
- name: Ensure Nginx is installed
|
||||
- name: Configure Nginx virtual host
|
||||
- name: Copy application configuration to server
|
||||
```
|
||||
|
||||
### Variable Usage
|
||||
|
||||
Agent reviews:
|
||||
- Variable namespacing (no conflicts)
|
||||
- Defined defaults
|
||||
- No hardcoded values
|
||||
- Proper precedence understanding
|
||||
|
||||
**Example Issues**:
|
||||
```yaml
|
||||
# BAD - Generic names, hardcoded
|
||||
port: 80
|
||||
user: webapp
|
||||
|
||||
# GOOD - Namespaced, from defaults
|
||||
nginx_port: "{{ nginx_default_port | default(80) }}"
|
||||
nginx_user: "{{ nginx_service_user | default('www-data') }}"
|
||||
```
|
||||
|
||||
### Handler Review
|
||||
|
||||
Agent checks:
|
||||
- Handlers for service restarts
|
||||
- Not direct task restarts
|
||||
- Handler names clear
|
||||
- Proper notify usage
|
||||
|
||||
**Example Issues**:
|
||||
```yaml
|
||||
# BAD - Direct restart
|
||||
- name: Update config
|
||||
ansible.builtin.template:
|
||||
src: nginx.conf.j2
|
||||
dest: /etc/nginx/nginx.conf
|
||||
|
||||
- name: Restart nginx
|
||||
ansible.builtin.service:
|
||||
name: nginx
|
||||
state: restarted
|
||||
|
||||
# GOOD - Using handler
|
||||
- name: Update configuration
|
||||
ansible.builtin.template:
|
||||
src: nginx.conf.j2
|
||||
dest: /etc/nginx/nginx.conf
|
||||
notify: Reload nginx
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Agent verifies:
|
||||
- Block/rescue for critical operations
|
||||
- Validation before destructive changes
|
||||
- Backup before modifications
|
||||
- Rollback mechanisms
|
||||
|
||||
**Example Issues**:
|
||||
```yaml
|
||||
# BAD - No error handling
|
||||
- name: Deploy new version
|
||||
ansible.builtin.copy:
|
||||
src: app.jar
|
||||
dest: /opt/app/app.jar
|
||||
|
||||
# GOOD - With rollback
|
||||
- name: Deploy with rollback
|
||||
block:
|
||||
- name: Backup current version
|
||||
ansible.builtin.copy:
|
||||
src: /opt/app/app.jar
|
||||
dest: /opt/app/app.jar.backup
|
||||
remote_src: yes
|
||||
|
||||
- name: Deploy new version
|
||||
ansible.builtin.copy:
|
||||
src: app.jar
|
||||
dest: /opt/app/app.jar
|
||||
|
||||
- name: Restart service
|
||||
ansible.builtin.service:
|
||||
name: myapp
|
||||
state: restarted
|
||||
|
||||
rescue:
|
||||
- name: Restore backup
|
||||
ansible.builtin.copy:
|
||||
src: /opt/app/app.jar.backup
|
||||
dest: /opt/app/app.jar
|
||||
remote_src: yes
|
||||
|
||||
- name: Restart with old version
|
||||
ansible.builtin.service:
|
||||
name: myapp
|
||||
state: restarted
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
### Code Review Report
|
||||
|
||||
**Summary**:
|
||||
- Overall Quality: [Excellent/Good/Needs Improvement/Poor]
|
||||
- Critical Issues: [count]
|
||||
- High Priority: [count]
|
||||
- Medium Priority: [count]
|
||||
- Low Priority: [count]
|
||||
- Idempotency Status: [✓ Pass / ✗ Fail]
|
||||
|
||||
**Critical Findings**:
|
||||
```
|
||||
[CRITICAL] Idempotency: Non-idempotent shell command
|
||||
Location: roles/nginx/tasks/main.yml:15
|
||||
Issue: Using shell to install package
|
||||
Impact: Task reports changed every run
|
||||
Fix: Use ansible.builtin.package module
|
||||
```
|
||||
|
||||
**Recommendations**:
|
||||
1. Fix critical idempotency issues immediately
|
||||
2. Replace shell/command with proper modules
|
||||
3. Add error handling to deployment tasks
|
||||
4. Improve task naming consistency
|
||||
5. Add validation before config changes
|
||||
|
||||
### Validation Commands
|
||||
|
||||
After fixing issues:
|
||||
```bash
|
||||
# Syntax check
|
||||
ansible-playbook playbook.yml --syntax-check
|
||||
|
||||
# Lint with fixes
|
||||
ansible-lint roles/ --fix
|
||||
|
||||
# Check mode to verify idempotency
|
||||
ansible-playbook playbook.yml --check
|
||||
ansible-playbook playbook.yml --check # Run twice
|
||||
|
||||
# Test in development
|
||||
ansible-playbook playbook.yml -i inventory/dev -vv
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
**Pre-Review**:
|
||||
- Run syntax check first
|
||||
- Run ansible-lint locally
|
||||
- Fix obvious issues before agent review
|
||||
|
||||
**During Review**:
|
||||
- Provide complete context
|
||||
- Specify environment criticality
|
||||
- Note any constraints or requirements
|
||||
- Ask about specific concerns
|
||||
|
||||
**Post-Review**:
|
||||
- Fix Critical and High issues first
|
||||
- Test fixes in development
|
||||
- Re-review after significant changes
|
||||
- Document rationale for any exceptions
|
||||
|
||||
**Continuous Improvement**:
|
||||
- Integrate ansible-lint in CI/CD
|
||||
- Regular code reviews before production
|
||||
- Keep roles modular and focused
|
||||
- Maintain consistent coding standards
|
||||
- Document patterns and decisions
|
||||
434
commands/review-ansible-security.md
Normal file
434
commands/review-ansible-security.md
Normal file
@@ -0,0 +1,434 @@
|
||||
---
|
||||
description: Security review of Ansible code
|
||||
argument-hint: Optional code to review
|
||||
---
|
||||
|
||||
# Ansible Security Review
|
||||
|
||||
You are conducting a security review of Ansible code for vulnerabilities, credential handling, privilege escalation, and compliance using the ansible-security-reviewer agent.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Identify Security Review Scope
|
||||
|
||||
Determine what requires security review:
|
||||
- **New code**: Before initial deployment
|
||||
- **Existing code**: Regular security audits
|
||||
- **Production code**: Before production deployment
|
||||
- **High-risk operations**: Privileged access, credential handling
|
||||
- **Compliance check**: PCI-DSS, HIPAA, GDPR, SOC2
|
||||
|
||||
### 2. Gather Code and Requirements
|
||||
|
||||
If not specified, ask for:
|
||||
- **Code to review**:
|
||||
- File paths or directories
|
||||
- Or paste code directly
|
||||
- **Environment criticality**:
|
||||
- Production (strict standards)
|
||||
- Staging (moderate standards)
|
||||
- Development (baseline standards)
|
||||
- **Compliance requirements**:
|
||||
- PCI-DSS (payment card data)
|
||||
- HIPAA (healthcare)
|
||||
- GDPR (EU data privacy)
|
||||
- SOC 2 (security controls)
|
||||
- CIS Benchmarks
|
||||
- **Specific security concerns**:
|
||||
- Credential management
|
||||
- Privilege escalation
|
||||
- File permissions
|
||||
- Network security
|
||||
- Supply chain security
|
||||
- **Risk tolerance**:
|
||||
- Zero tolerance (financial, healthcare)
|
||||
- Moderate (enterprise)
|
||||
- Standard (general business)
|
||||
|
||||
### 3. Pre-Security Scan
|
||||
|
||||
Run automated security scans first:
|
||||
|
||||
```bash
|
||||
# Check for hardcoded secrets
|
||||
trufflehog filesystem . --only-verified
|
||||
|
||||
# Git secrets scan
|
||||
git secrets --scan
|
||||
|
||||
# ansible-lint security profile
|
||||
ansible-lint --profile security roles/
|
||||
|
||||
# Check vault files are encrypted
|
||||
find . -name "vault*.yml" -exec ansible-vault view {} \;
|
||||
```
|
||||
|
||||
### 4. Launch Security Reviewer
|
||||
|
||||
Launch **ansible-security-reviewer** with:
|
||||
```
|
||||
"Perform security review of Ansible code at [location].
|
||||
Environment: [production/staging/development]
|
||||
Compliance: [requirements if any]
|
||||
Risk tolerance: [zero/moderate/standard]
|
||||
|
||||
Focus on:
|
||||
- Hardcoded credentials and secrets
|
||||
- Ansible Vault usage
|
||||
- Privilege escalation (become/sudo)
|
||||
- File and directory permissions
|
||||
- Command injection risks
|
||||
- Template injection risks
|
||||
- Network security (HTTPS, certs)
|
||||
- Logging secrets (no_log)
|
||||
- Supply chain security
|
||||
- Audit and compliance"
|
||||
```
|
||||
|
||||
### 5. Analyze Security Findings
|
||||
|
||||
Agent categorizes by severity:
|
||||
|
||||
**Critical** (Block all deployment):
|
||||
- Hardcoded passwords, API keys, tokens
|
||||
- Credentials in unencrypted files
|
||||
- Credentials committed to Git
|
||||
- Missing Ansible Vault
|
||||
- World-readable sensitive files
|
||||
- Command injection vulnerabilities
|
||||
- Privileged containers without justification
|
||||
|
||||
**High** (Fix before production):
|
||||
- Secrets in logs (missing `no_log`)
|
||||
- Excessive privilege escalation
|
||||
- Weak file permissions on sensitive files
|
||||
- Disabled certificate validation
|
||||
- No backup before destructive operations
|
||||
- Missing input validation
|
||||
- Unencrypted network protocols
|
||||
|
||||
**Medium** (Address within sprint):
|
||||
- Generic variable names (potential conflicts)
|
||||
- No audit logging
|
||||
- Supply chain: unpinned versions
|
||||
- Missing security headers
|
||||
- Verbose logging in production
|
||||
- No secrets rotation plan
|
||||
|
||||
**Low** (Best practice improvements):
|
||||
- Could use stricter permissions
|
||||
- Documentation of security decisions
|
||||
- Security testing gaps
|
||||
- Monitoring improvements
|
||||
|
||||
### 6. Remediation Planning
|
||||
|
||||
Create security fix plan:
|
||||
|
||||
**Immediate** (0-24 hours):
|
||||
1. Remove all hardcoded credentials
|
||||
2. Encrypt with Ansible Vault
|
||||
3. Fix critical file permissions
|
||||
4. Add `no_log` to sensitive tasks
|
||||
|
||||
**Short-term** (1-7 days):
|
||||
1. Implement external secret management
|
||||
2. Reduce privilege escalation
|
||||
3. Fix injection vulnerabilities
|
||||
4. Enable certificate validation
|
||||
5. Add audit logging
|
||||
|
||||
**Long-term** (1-3 months):
|
||||
1. Migrate to HashiCorp Vault / AWS Secrets Manager
|
||||
2. Implement secret rotation
|
||||
3. Security scanning in CI/CD
|
||||
4. Regular security audits
|
||||
|
||||
## Security Review Categories
|
||||
|
||||
### Credential Management
|
||||
|
||||
Agent scans for:
|
||||
- Hardcoded passwords
|
||||
- API keys in plain text
|
||||
- SSH keys in code
|
||||
- Database credentials
|
||||
- Certificates and private keys
|
||||
- Unencrypted vault files
|
||||
|
||||
**Critical Issues**:
|
||||
```yaml
|
||||
# CRITICAL - Hardcoded password
|
||||
- name: Create database user
|
||||
postgresql_user:
|
||||
name: appuser
|
||||
password: "SuperSecret123!" # EXPOSED!
|
||||
|
||||
# FIX - Use Vault
|
||||
- name: Create database user
|
||||
postgresql_user:
|
||||
name: appuser
|
||||
password: "{{ vault_db_password }}"
|
||||
no_log: true
|
||||
```
|
||||
|
||||
### Privilege Escalation
|
||||
|
||||
Agent checks:
|
||||
- Unnecessary root/sudo usage
|
||||
- Overly broad sudo permissions
|
||||
- become_user validation
|
||||
- Principle of least privilege
|
||||
|
||||
**Issues**:
|
||||
```yaml
|
||||
# BAD - Unnecessary root
|
||||
- name: Create user file
|
||||
become: yes
|
||||
become_user: root
|
||||
ansible.builtin.copy:
|
||||
src: user_config
|
||||
dest: /home/appuser/.config
|
||||
|
||||
# GOOD - Run as user
|
||||
- name: Create user file
|
||||
become: yes
|
||||
become_user: appuser
|
||||
ansible.builtin.copy:
|
||||
src: user_config
|
||||
dest: /home/appuser/.config
|
||||
```
|
||||
|
||||
### File Permissions
|
||||
|
||||
Agent verifies:
|
||||
- Sensitive files not world-readable
|
||||
- Directories properly restricted
|
||||
- SSH config and keys secured
|
||||
- Vault files protected
|
||||
|
||||
**Critical Issues**:
|
||||
```yaml
|
||||
# CRITICAL - World readable
|
||||
- name: Create SSH private key
|
||||
ansible.builtin.copy:
|
||||
src: id_rsa
|
||||
dest: /home/user/.ssh/id_rsa
|
||||
# Missing mode! Defaults to 0644
|
||||
|
||||
# FIX - Proper permissions
|
||||
- name: Create SSH private key
|
||||
ansible.builtin.copy:
|
||||
src: id_rsa
|
||||
dest: /home/user/.ssh/id_rsa
|
||||
owner: user
|
||||
group: user
|
||||
mode: '0400' # Read-only by owner
|
||||
```
|
||||
|
||||
### Command Injection
|
||||
|
||||
Agent identifies:
|
||||
- Unsanitized variables in shell
|
||||
- SQL injection in database commands
|
||||
- Unquoted variables in commands
|
||||
|
||||
**Critical Issues**:
|
||||
```yaml
|
||||
# CRITICAL - Command injection
|
||||
- name: Process user input
|
||||
ansible.builtin.shell: echo "{{ user_input }}" > /tmp/file
|
||||
# user_input could be: "; rm -rf / #"
|
||||
|
||||
# FIX - Use copy module
|
||||
- name: Write user input safely
|
||||
ansible.builtin.copy:
|
||||
content: "{{ user_input }}"
|
||||
dest: /tmp/file
|
||||
```
|
||||
|
||||
### Secrets in Logs
|
||||
|
||||
Agent checks for:
|
||||
- Missing `no_log` on sensitive tasks
|
||||
- Debug statements with secrets
|
||||
- Verbose logging of credentials
|
||||
|
||||
**Issues**:
|
||||
```yaml
|
||||
# BAD - Password in logs
|
||||
- name: Set database password
|
||||
ansible.builtin.lineinfile:
|
||||
path: /etc/app/config.ini
|
||||
line: "password={{ db_password }}"
|
||||
# Password appears in logs!
|
||||
|
||||
# GOOD - no_log enabled
|
||||
- name: Set database password
|
||||
ansible.builtin.lineinfile:
|
||||
path: /etc/app/config.ini
|
||||
line: "password={{ db_password }}"
|
||||
no_log: true
|
||||
```
|
||||
|
||||
### Network Security
|
||||
|
||||
Agent reviews:
|
||||
- HTTP vs HTTPS
|
||||
- Certificate validation
|
||||
- Secure protocols
|
||||
- Exposed services
|
||||
|
||||
**Issues**:
|
||||
```yaml
|
||||
# BAD - Disabled cert validation
|
||||
- name: Download file
|
||||
ansible.builtin.get_url:
|
||||
url: https://example.com/file
|
||||
dest: /tmp/file
|
||||
validate_certs: no # SECURITY RISK!
|
||||
|
||||
# GOOD - Cert validation enabled
|
||||
- name: Download file
|
||||
ansible.builtin.get_url:
|
||||
url: https://example.com/file
|
||||
dest: /tmp/file
|
||||
validate_certs: yes
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
### Security Review Report
|
||||
|
||||
**Executive Summary**:
|
||||
- Overall Security Posture: [Critical Risk/High Risk/Medium Risk/Low Risk]
|
||||
- Critical Findings: [count] - MUST FIX IMMEDIATELY
|
||||
- High Findings: [count] - Fix before production
|
||||
- Medium Findings: [count] - Address within sprint
|
||||
- Low Findings: [count] - Best practice improvements
|
||||
- Compliance Status: [Pass/Fail per requirement]
|
||||
|
||||
**Critical Security Findings**:
|
||||
```
|
||||
[CRITICAL] Credential Management: Hardcoded Password
|
||||
Location: roles/database/tasks/main.yml:25
|
||||
Vulnerability: Database password in plain text
|
||||
Evidence:
|
||||
password: "SuperSecret123!"
|
||||
Risk:
|
||||
- Credentials exposed in version control
|
||||
- No ability to rotate passwords
|
||||
- Violates PCI-DSS 8.2.1, GDPR Article 32
|
||||
Recommendation:
|
||||
1. Remove hardcoded password
|
||||
2. Encrypt with: ansible-vault encrypt_string 'password' --name 'vault_db_password'
|
||||
3. Use: password: "{{ vault_db_password }}"
|
||||
4. Add: no_log: true
|
||||
```
|
||||
|
||||
**Security Checklist**:
|
||||
- [ ] No hardcoded credentials
|
||||
- [ ] Ansible Vault for all secrets
|
||||
- [ ] `no_log` on sensitive tasks
|
||||
- [ ] Minimal privilege escalation
|
||||
- [ ] Secure file permissions (0600/0400 for secrets)
|
||||
- [ ] No command injection vectors
|
||||
- [ ] HTTPS with certificate validation
|
||||
- [ ] Audit logging enabled
|
||||
- [ ] Supply chain: pinned versions
|
||||
- [ ] Backup before destructive operations
|
||||
|
||||
**Remediation Priority**:
|
||||
|
||||
**Immediate (0-24 hours)**:
|
||||
1. Remove hardcoded password at roles/database/tasks/main.yml:25
|
||||
2. Fix world-readable SSH key at roles/deploy/files/id_rsa
|
||||
3. Add no_log to vault password task at roles/vault/tasks/main.yml:10
|
||||
|
||||
**Short-term (1-7 days)**:
|
||||
1. Implement Ansible Vault for all secrets
|
||||
2. Reduce unnecessary sudo/root usage
|
||||
3. Enable certificate validation
|
||||
4. Add audit logging
|
||||
|
||||
**Long-term (1-3 months)**:
|
||||
1. Migrate to HashiCorp Vault
|
||||
2. Implement secrets rotation
|
||||
3. Security CI/CD integration
|
||||
4. Regular penetration testing
|
||||
|
||||
### Validation Commands
|
||||
|
||||
After fixing security issues:
|
||||
|
||||
```bash
|
||||
# Scan for secrets
|
||||
trufflehog filesystem . --only-verified
|
||||
|
||||
# Verify vault encryption
|
||||
find . -name "vault*.yml" -exec file {} \;
|
||||
# Should show "data" not "ASCII text"
|
||||
|
||||
# Security lint
|
||||
ansible-lint --profile security roles/
|
||||
|
||||
# Verify no secrets in git history
|
||||
git log -p | grep -i "password\|secret\|key"
|
||||
|
||||
# Test with production-like settings
|
||||
ansible-playbook playbook.yml --check -i inventory/production
|
||||
```
|
||||
|
||||
## Compliance Frameworks
|
||||
|
||||
### PCI-DSS Requirements
|
||||
- No cardholder data in logs (Req 3.4)
|
||||
- Strong access controls (Req 7)
|
||||
- Encrypted transmission (Req 4)
|
||||
- Audit trails (Req 10)
|
||||
|
||||
### HIPAA Requirements
|
||||
- PHI encryption at rest and transit
|
||||
- Access controls and audit logging
|
||||
- Regular security assessments
|
||||
- Breach notification procedures
|
||||
|
||||
### GDPR Requirements
|
||||
- Data encryption (Article 32)
|
||||
- Access controls (Article 32)
|
||||
- Audit logging (Article 30)
|
||||
- Data minimization (Article 5)
|
||||
|
||||
### SOC 2 Requirements
|
||||
- Access controls (CC6.1)
|
||||
- Encryption (CC6.7)
|
||||
- Change management (CC8.1)
|
||||
- Monitoring and logging (CC7.2)
|
||||
|
||||
## Best Practices
|
||||
|
||||
**Pre-Review**:
|
||||
- Run automated secret scans
|
||||
- Check all vault files encrypted
|
||||
- Review git history for leaked secrets
|
||||
- Document security requirements
|
||||
|
||||
**During Review**:
|
||||
- Specify compliance requirements
|
||||
- Note environment criticality
|
||||
- Identify high-risk operations
|
||||
- Provide complete context
|
||||
|
||||
**Post-Review**:
|
||||
- Fix Critical issues immediately
|
||||
- Never deploy with Critical findings
|
||||
- Document security decisions
|
||||
- Re-review after changes
|
||||
|
||||
**Continuous Security**:
|
||||
- Integrate security scanning in CI/CD
|
||||
- Regular security audits (quarterly)
|
||||
- Rotate secrets regularly
|
||||
- Monitor security advisories
|
||||
- Keep Ansible and collections updated
|
||||
- Train team on secure coding practices
|
||||
Reference in New Issue
Block a user