Interview › Infrastructure as Code (Terraform, Ansible)
What is the difference between declarative and imperative IaC, and where do Terraform and Ansible fall?
Infrastructure as Code (Terraform, Ansible) · Basic level
Answer
Declarative IaC describes the desired end state and lets the tool calculate the changes. Imperative automation describes the exact steps to run. Terraform is primarily declarative. Ansible runs ordered tasks, so it feels imperative, but its modules are designed to be idempotent and express desired state such as package present or service started.
Technical explanation
Declarative tools require accurate state or discovery to calculate delta safely.
Imperative tasks are useful when order matters, such as draining a node before patching it.
Many production platforms combine both: Terraform for resources and Ansible for ordered host operations.
Keep Terraform's ownership boundary clear: one state should own a resource or field, and other tools should consume published outputs instead of modifying it.
Use fmt, validate, linting, policy checks, plan review, and state locking before production applies.
Design for small blast radius by splitting state around lifecycle, permissions, and recovery boundaries.
Hands-on example
1. Build a small IaC workflow for: What is the difference between declarative and imperative IaC, and where do Terraform and Ansible fall?
2. Create a Git repository with folders terraform/network and ansible/web. Put cloud resources in Terraform and host configuration in Ansible.
3. Add a minimal Terraform resource and run the standard workflow:
cd terraform/network
terraform init
terraform fmt -check
terraform validate
terraform plan -out=tfplan
terraform apply tfplan
4. Commit the plan output summary to the pull request, require approval, then use Ansible after infrastructure exists:
ansible-inventory -i inventory/aws_ec2.yml --graph
ansible-playbook -i inventory/aws_ec2.yml ansible/web/site.yml --check --diff
ansible-playbook -i inventory/aws_ec2.yml ansible/web/site.yml
5. Prove the benefit by rebuilding a dev environment from Git and confirming there are no manual console steps.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Infrastructure as Code (Terraform, Ansible) interview questions
- What is Infrastructure as Code, and what problems does it solve over click-ops?
- What is the difference between configuration management and provisioning?
- What is Terraform, and what is the core plan/apply workflow?
- What does terraform init do?
- What is the Terraform state file, and why is it critical?
- Why should state be stored remotely, and what backend would you use on AWS?
- What is state locking, and why does it matter for teams?
- How does Terraform use DynamoDB for state locking with an S3 backend?