Terraform provisions the sandbox infrastructure. Ansible discovers hosts, configures systems and deploys the application. CI validates changes and gates deployment with approvals.
01 · PLANTerraform creates network and compute resources
Git repository, CI runner, Ansible execution environment, inventory plugins and protected credentials.
Managed environment
Sandbox Linux hosts, application service, container runtime where required, and health-check endpoints.
Important: Terraform and Ansible have separate responsibilities. Terraform owns infrastructure resources; Ansible owns operating-system and application configuration. Avoid managing the same setting with both tools.
03 / SETUP
Prepare your advanced lab environment
Use a disposable cloud sandbox or local virtual machines. Do not begin with production credentials or production servers.
CONTROL NODE
Automation workstation
Linux, Python, pinned Ansible Core, Git, SSH client and access to the repository.
TARGETS
Managed Linux hosts
At least two test hosts reachable over SSH, with a dedicated automation account and approved privilege escalation.
CI/CD
GitHub repository
A repository with Actions enabled, protected branches and a test environment. Production deployment is intentionally not enabled in this lab.
OPTIONAL INTEGRATION
Terraform and Docker
A Terraform sandbox for provisioning and Docker only if your chosen application is containerised.
Install and verify the tooling
python3 --version
git --version
ansible --version
Install Ansible using your organisation's approved method. Pin the Ansible Core and collection versions used by this project rather than relying on an unbounded latest version.
Security note: Keep private SSH keys, cloud credentials, Vault passwords and API tokens out of Git. Use a sandbox and verify SSH host fingerprints; do not disable host-key checking to make a connection succeed.
04 / PROJECT STRUCTURE
Create a maintainable automation repository
Separate inventories, playbooks, roles, collection dependencies, tests and CI workflows so each part can be reviewed independently.
Recommended repository layout
Your task: Create this structure in a new Git repository. Keep environment-specific inventory and variables separate. Add only non-secret defaults to version control; encrypted Vault files may be committed only when your team’s key-management policy permits it.
05 / DYNAMIC INVENTORY
Discover hosts without hard-coding every IP
Dynamic inventory plugins query an approved source, such as a cloud API, and return hosts and metadata to Ansible. The example below shows the inventory workflow, not cloud credentials.
Static inventory
Useful for a small fixed lab. Hostnames and addresses are maintained manually.
Dynamic inventory
Useful when infrastructure changes frequently. A plugin retrieves hosts from a supported source using scoped credentials.
inventory/test.ini
For cloud discovery, install the provider collection documented for your cloud, configure its inventory plugin, and authenticate using a short-lived identity. Do not paste access keys into the inventory file.
Before execution: Confirm the inventory resolves only to your authorised sandbox hosts. Dynamic inventory can expand the target set unexpectedly if filters or account scope are too broad.
06 / ADVANCED PLAYBOOKS
Build safer, reusable automation
Use task files, imports and includes to keep playbooks readable. Use rolling batches and health checks to reduce deployment risk.
site.yml
Imports and includes
Use import_tasks for static reuse and include_tasks when task inclusion must be evaluated dynamically, such as inside a loop or conditional.
Delegation
Use delegate_to for tasks that must run from another host, such as a load-balancer drain or a central orchestration action. Understand which host owns each variable.
Async execution
Use async and poll deliberately for long-running tasks. Set a realistic timeout and verify completion rather than assuming a background task succeeded.
Rolling updates
Use serial batches, remove hosts from traffic where appropriate, deploy, check service health and restore traffic before proceeding.
Collection practice: Prefer fully qualified collection names such as ansible.builtin.service. Review third-party collection maintainers, permissions, release history and compatibility before installing.
07 / SECURITY & VAULT
Protect secrets and control access
Encrypt sensitive variables, restrict who can decrypt them, and keep decrypted values out of logs and build artifacts.
Vault commands
Identity
Use dedicated automation accounts, verified SSH host keys and least-privilege sudo rules.
Credentials
Use Vault or an external secret manager. Rotate credentials and scope access by environment.
Auditability
Review who can run privileged playbooks, access inventories and approve production changes.
Vault limitation: Vault encrypts data at rest; it does not automatically protect secrets after decryption. Avoid debug output, verbose logs and CI artifacts that could reveal secret values.
08 / TESTING & TROUBLESHOOTING
Validate before deployment
Syntax checks catch structural errors. Linting catches common issues. Role tests and integration tests help confirm actual behaviour on target systems.
Use Molecule where appropriate to create disposable test instances, converge a role, verify behaviour and destroy the test environment.
Idempotency
Run the playbook twice. Investigate unexpected changes on the second run; a stable configuration should not repeatedly modify the same resources.
Failure diagnosis
Check SSH reachability, Python interpreter discovery, become permissions, collection versions, YAML structure and OS compatibility.
Health verification
Test the application endpoint and service state after deployment. Include failure handling and rollback or forward-fix procedures.
Remember: Check mode is not a substitute for testing. Some modules do not support full simulation, and a syntax check does not prove that tasks will succeed on every host.
09 / CI/CD PIPELINE
Automate validation with GitHub Actions
Start with a validation-only pipeline. It checks the repository on pull requests and pushes; it does not deploy to managed servers or use production credentials.
.github/workflows/ansible-validation.yml
Validation stage
Checkout, install pinned tooling, install declared collections, run syntax checks and lint. Add role tests before enabling deployment.
Protected deployment stage
Use a separate job with environment approval, restricted runner access, scoped secrets and an explicit inventory limit. Never expose production credentials to untrusted pull requests.
Production gate: Keep apply/deploy separate from pull-request validation. Require human approval, verify the exact target environment and ensure rollback steps are documented before adding deployment credentials.
10 / END-TO-END PROJECT
Deliver a cloud-hosted application
Combine Terraform, Ansible and CI/CD in one controlled workflow. Use a sandbox account and a small application that can be deployed and verified safely.
01 · PROVISIONTerraform creates sandbox network and compute
03 · DEPLOYRoles configure runtime and application
04 · VERIFYPipeline checks health and records results
Project deliverables
Terraform configuration, dynamic or generated inventory, reusable Ansible roles, encrypted variables, CI validation workflow, deployment notes and architecture diagram.
Required evidence
Successful validation logs, test results, deployment output, application health check, idempotency evidence, approval record and cleanup confirmation.
Completion checklist
Cost and cleanup: Cloud resources can incur charges. Record what you created, verify the resources belong to your lab, and destroy disposable infrastructure after collecting evidence.
11 / KNOWLEDGE CHECK
Test your understanding
1. What is a key benefit of dynamic inventory?
2. What does Ansible Vault primarily protect?
3. What should happen before a production deployment?