# Ansible vs Terraform in 2026: Infrastructure as Code and DevOps Interview Questions > Compare Ansible vs Terraform for infrastructure as code in 2026. Understand configuration management vs provisioning, when to use each tool, and prepare for DevOps interview questions. - Published: 2026-08-22 - Updated: 2026-08-22 - Author: Anthony Fillion-Maillet - Tags: ansible, terraform, infrastructure-as-code, devops, interview - Reading time: 12 min --- Ansible vs Terraform represents one of the most common comparison questions in DevOps interviews, yet the framing itself reveals a misunderstanding: these tools solve different problems. Ansible 2.20 handles configuration management and application deployment, while Terraform 1.15 provisions infrastructure resources. Understanding when each excels, where they overlap, and how they complement each other separates senior DevOps engineers from those still learning the fundamentals. > **The Core Distinction** > > Terraform manages infrastructure state declaratively (VMs, networks, databases). Ansible configures what runs on that infrastructure procedurally (packages, services, files). Most production environments use both. ## Declarative vs Procedural: The Fundamental Difference Terraform uses a declarative approach. A configuration file describes the desired end state, and Terraform calculates the necessary changes to reach it. This works well for infrastructure that needs to be created, modified, or destroyed as a unit. ```hcl # main.tf resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t3.medium" tags = { Name = "web-server" Environment = "production" } } resource "aws_security_group" "web" { name = "web-sg" description = "Allow HTTP and HTTPS" ingress { from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } } ``` Running `terraform apply` creates both resources if they do not exist, or updates them to match the configuration. Running it again with no changes produces no operations: Terraform compares the configuration against its state file and finds nothing to do. Ansible uses a procedural approach with tasks executed in order. While Ansible modules are often idempotent (running them twice produces the same result), the playbook itself describes a sequence of actions rather than an end state. ```yaml # webserver.yml - name: Configure web server hosts: webservers become: true tasks: - name: Install nginx ansible.builtin.apt: name: nginx state: present update_cache: true - name: Copy nginx configuration ansible.builtin.template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: Restart nginx - name: Ensure nginx is running ansible.builtin.service: name: nginx state: started enabled: true handlers: - name: Restart nginx ansible.builtin.service: name: nginx state: restarted ``` Each task runs in sequence. The notify/handler pattern provides some declarative behavior: the handler runs only once at the end, regardless of how many tasks trigger it. ## State Management: A Critical Interview Topic Terraform maintains a [state file](https://developer.hashicorp.com/terraform/language/state) that maps configuration to real resources. This state tracks resource IDs, dependencies, and metadata. Without it, Terraform cannot determine what exists or what needs changing. | Aspect | Terraform | Ansible | |--------|-----------|----------| | State storage | Required (local file or remote backend) | None by default | | Drift detection | Built-in via `terraform plan` | Requires explicit checks | | Resource tracking | Automatic through state | Inventory-based | | Rollback | Destroy and recreate from state | No native rollback | Ansible has no equivalent state file. It connects to target systems and executes tasks, relying on the current system state and module idempotency. This makes Ansible simpler to start with but harder to track changes over time. A common interview question asks about state file security. Terraform state can contain sensitive data: database passwords, API keys, resource identifiers. Production deployments store state remotely (S3, Azure Blob, Terraform Cloud) with encryption and access controls. ```hcl # backend.tf terraform { backend "s3" { bucket = "company-terraform-state" key = "prod/infrastructure.tfstate" region = "us-east-1" encrypt = true dynamodb_table = "terraform-locks" } } ``` The DynamoDB table provides locking, preventing two engineers from modifying state simultaneously. ## When to Use Each Tool Terraform excels at provisioning cloud infrastructure: virtual machines, managed databases, load balancers, IAM roles, VPCs. It handles dependencies between resources automatically and supports all major cloud providers through a consistent HCL syntax. Ansible excels at configuring existing systems: installing packages, managing users, deploying application code, orchestrating multi-step deployments. It connects over SSH (or WinRM for Windows) without requiring agents on target machines. The overlap zone causes confusion. Both can install software on a VM. Terraform can use [provisioners](https://developer.hashicorp.com/terraform/language/resources/provisioners/syntax) to run scripts after resource creation. Ansible can create cloud resources through modules like `amazon.aws.ec2_instance`. But using each tool outside its strength leads to maintainability problems. > **Avoid This Anti-Pattern** > > Using Terraform provisioners extensively for configuration management creates fragile infrastructure. Provisioners run only at creation time, not on subsequent applies. Use Terraform for infrastructure, then hand off to Ansible for configuration. ## The Combined Workflow in Production Most organizations use both tools together. Terraform provisions the infrastructure and outputs connection details. Ansible consumes those outputs to configure the systems. ```hcl # outputs.tf output "web_server_ips" { value = aws_instance.web[*].private_ip description = "Private IPs of web servers" } output "db_endpoint" { value = aws_rds_instance.main.endpoint description = "RDS endpoint for application config" } ``` A CI/CD pipeline runs Terraform first, captures outputs, generates an Ansible inventory dynamically, then runs playbooks against the new infrastructure. ```yaml # ansible/inventory/aws_ec2.yml plugin: amazon.aws.aws_ec2 regions: - us-east-1 filters: tag:Environment: production instance-state-name: running hostnames: - private-ip-address groups: webservers: "'web' in tags.Role" databases: "'db' in tags.Role" ``` This dynamic inventory queries AWS directly, grouping instances by their tags. No manual IP management required. ## OpenTofu: The Fork That Changed the Landscape HashiCorp relicensed Terraform under the Business Source License (BSL) in August 2023. The community responded by forking Terraform 1.5 into [OpenTofu](https://opentofu.org/), now hosted under the Linux Foundation. As of August 2026, OpenTofu 1.11.6 remains a drop-in replacement for most Terraform workflows. The same HCL syntax, the same provider ecosystem, the same state format. OpenTofu has added features not present in Terraform's open-source binary: state encryption, provider `for_each`, and early variable evaluation. For interview preparation, understand the licensing distinction. BSL permits internal use but restricts building competing products. Organizations concerned about vendor lock-in or with specific compliance requirements may prefer OpenTofu's MPL 2.0 license. IBM's acquisition of HashiCorp in December 2024 added another variable to vendor relationship discussions. ## Common DevOps Interview Questions **Q: Can Ansible replace Terraform?** Not effectively. Ansible can create cloud resources, but it lacks state management. Running the same playbook twice might create duplicate resources. Terraform's state file tracks what exists and calculates minimal changes. Use Ansible for what it does best: configuration management. **Q: How do you handle secrets in Terraform?** Never commit secrets to version control. Use environment variables, Vault integration, or cloud provider secret managers. Mark variables as sensitive to prevent them appearing in logs: ```hcl # variables.tf variable "db_password" { type = string sensitive = true description = "Database password from Vault or environment" } ``` **Q: What is Ansible idempotency?** An idempotent operation produces the same result whether run once or multiple times. The `apt` module with `state: present` installs a package if missing and does nothing if already installed. Writing idempotent playbooks prevents unintended changes on subsequent runs. **Q: How do you test infrastructure code?** Terraform: `terraform validate` checks syntax, `terraform plan` previews changes, and tools like [Terratest](https://terratest.gruntwork.io/) run integration tests. Ansible: `ansible-lint` catches issues, `--check` mode performs dry runs, and [Molecule](https://ansible.readthedocs.io/projects/molecule/) tests roles against containers. For deeper Terraform interview preparation, see [Terraform Interview Questions: Infrastructure as Code Complete Guide](/blog/devops/terraform-interview-questions-infrastructure-as-code). Practice hands-on with [Terraform Basics](/technologies/devops/interview-questions/terraform-basics) and [Ansible Configuration Management](/technologies/devops/interview-questions/ansible-configuration) modules. ## Version Compatibility and Ecosystem Current stable versions as of August 2026: | Tool | Version | Release Date | Key Feature | |------|---------|--------------|-------------| | Ansible | 2.20.5 | April 2026 | Improved collection management | | Terraform | 1.15.8 | July 2026 | Windows ARM64 support, convert function | | OpenTofu | 1.11.6 | April 2026 | State encryption, provider for_each | Ansible's collection architecture separates core functionality from provider-specific modules. The `amazon.aws` collection receives updates independently of Ansible core. This matters for version pinning in CI/CD pipelines. Terraform's provider versioning follows similar principles. Lock files (`terraform.lock.hcl`) ensure consistent provider versions across team members and CI systems. ```hcl # versions.tf terraform { required_version = ">= 1.15.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.60" } } } ``` ## Choosing Between Them: A Decision Framework The question is rarely Ansible or Terraform. The question is which tool handles which responsibility. | Use Case | Recommended Tool | |----------|------------------| | Provision VMs, databases, networks | Terraform | | Configure OS, install packages | Ansible | | Manage Kubernetes resources | Terraform or kubectl/Helm | | Deploy application code | Ansible or CI/CD native | | Create IAM roles and policies | Terraform | | Manage user accounts on servers | Ansible | | Set up monitoring infrastructure | Terraform (create resources) + Ansible (configure agents) | For a complete picture of how these tools fit into modern deployment workflows, see [CI/CD Pipeline Interview Questions](/blog/devops/ci-cd-pipeline-interview-questions-github-actions-gitlab-ci-jenkins). ## What Senior Engineers Should Know About Ansible and Terraform - Terraform manages infrastructure state declaratively; Ansible configures systems procedurally. Using both together produces maintainable infrastructure. - State file security matters. Store Terraform state remotely with encryption and locking enabled. - OpenTofu provides an MPL-licensed alternative to Terraform with additional features. Migration is straightforward for most workflows. - Idempotency is not automatic. Write playbooks that produce consistent results on repeated runs. - Dynamic inventory eliminates manual host management. Query cloud providers directly for current infrastructure. - Version pinning prevents surprises. Lock provider versions in Terraform; pin collection versions in Ansible. - Testing infrastructure code requires different approaches: `terraform plan` for previewing changes, `--check` mode for Ansible dry runs, integration test frameworks for both. --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/en/blog/devops/ansible-vs-terraform-2026-infrastructure-as-code-devops-interview