Anyone who works in IT administration knows the importance of infrastructure automation for efficient and scalable IT operations. When you use Ansible with Terraform – two super powerful tools come together that enable seamless provisioning and infrastructure configuration. On one hand, Terraform focuses on Infrastructure as a Code (IaC) to create and manage cloud resources, while Ansible automates post provisioning configuration, application deployment, and system requirements.
Using Ansible with Terraform resolve multiple infrastructure issues and achieve a fully automated infrastructure deployment and management.
Understanding the Basics of Using Ansible with Terraform
Understanding the roles of each tool is essential for successfully setting up Ansible with Terraform.
What is Terraform?
Infrastructure as Code tool that automates cloud infrastructure deployment. It allows the user to define infrastructure using declarative configuration files. Supports multiple cloud providers like AWS, Azure, and Google Cloud.
Key Features:
Get exclusive access to all things tech-savvy, and be the first to receive
the latest updates directly in your inbox.
- Declarative Syntax – Define the desired state of infrastructure.
- Immutable Infrastructure – Changes are applied by recreating resources.
- State Management – Tracks infrastructure changes via a state file.
What is Ansible?
Ansible is a configuration management and automation tool that is agentless, using SSH or WinRM for remote execution.
Key Features:
- Agentless – No need to install software on remote servers.
- Idempotent – Ensures consistent configurations without unintended changes.
- Uses Playbooks – YAML-based scripts define tasks and configurations.
By combining Terraform and Ansible, you can provision, configure, and maintain infrastructure with minimal manual intervention.
Feature | Terraform | Ansible |
Purpose | Infrastructure provisioning | Configuration management & automation |
Execution | Declarative (desired state) | Procedural (step-by-step tasks) |
State Management | Uses state files | Does not maintain state |
Primary Use Case | Creating and managing infrastructure | Configuring software and maintaining systems |
Examples | Creating an AWS EC2 instance | Installing and configuring Apache on EC2 |
When to use Ansible with Terraform – Common Use Cases
It can be challenging to figure out when you need to integrate Ansible with Terraform, so here are the top such case scenarios.
- Multi-Cloud Infrastructure Management
- Automated Environment Setup
- Infrastructure as Code with Continuous Deployment
- Scaling and Upgrading Infrastructure
- Disaster Recovery and Replication
How to use Ansible with Terraform?
It is super easy to integrate Ansible with Terraform. Here is how you can easily set up with a few steps.
Setting Up Terraform with Ansible
Before you integrate Ansible with Terraform, you need to install and configure both tools properly.
Step 1: Install Terraform
- Download Terraform from the official website.
- Install Terraform using the package manager for your OS.
Ubuntu/Debian:
sudo apt update && sudo apt install -y terraform
MacOS (Homebrew):
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Windows: Use Chocolatey or download the binary manually.
- Verify the installation by running terraform -v.
Step 2: Install Ansible
- Install Ansible using the package manager:
Ubuntu/Debian:
sudo apt update && sudo apt install -y ansible
MacOS:
brew install ansible
Windows: Use WSL or install via Python:
pip install ansible
- Verify the installation:
ansible –version
Step 3: Configure Terraform and Ansible
Set up Terraform providers (AWS, Azure, Google Cloud). Generate SSH keys for Ansible to connect to provisioned instances:
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -q -N “”
Ensure Python is installed on remote servers for Ansible execution.
Using Terraform to Provision Infrastructure
Step 1: Create a Terraform Configuration File
Create a new directory and a file named main.tf:
mkdir terraform-ansible && cd terraform-ansible
nano main.tf
Step 2: Define the Terraform Script
Example of provisioning an AWS EC2 instance:
Step 3: Initialize and Apply Terraform
Run the following commands:
terraform init
terraform apply -auto-approve
Terraform will create the infrastructure and output the instance’s public IP.
Integrating Ansible with Terraform
Now that the basic setup is in place, you can easily integrate Ansible with Terraform.
Step 1: Create an Ansible Inventory File
Create inventory.ini file by:
Step 2: Create an Ansible Playbook
Create a file named setup.yml:
Step 3: Run Ansible Playbook from Terraform
Modify main.tf to include an Ansible local-exec provisioner:
resource “null_resource” “ansible_provision” {
depends_on = [aws_instance.web]
provisioner “local-exec” {
command = “ansible-playbook -i inventory.ini setup.yml”
}
}
Step 4: Apply Terraform Again
Run the command again to provision the infrastructure and configure it with Ansible:
terraform apply -auto-approve
Example: Deploying a Web Server Using Terraform and Ansible
This example shows:
- Using Terraform to provision an AWS EC2 instance.
- Using Ansible to install and configure an Nginx web server.
- Testing the deployment by accessing the web server.
Step 1: Creating Infrastructure with Terraform
1.1. Create a Terraform Configuration File
Inside a new project directory, create a file called main.tf:
1.2. Initialize and Apply Terraform
Step 2: Configuring the Server with Ansible
2.1. Create an Ansible Inventory File
Create inventory.ini:
To make Terraform generate this file dynamically, create a generate_inventory.sh script:
Run it after applying Terraform:
bash generate_inventory.sh
2.2. Create an Ansible Playbook (setup.yml)
This playbook will install and configure Nginx:
2.3. Run Ansible Playbook
Execute the playbook to configure the server:
ansible-playbook -i inventory.ini setup.yml
Step 3: Testing the Deployment
3.1. Get the Public IP
Retrieve the instance’s IP from Terraform:
terraform output -raw instance_ip
3.2. Test Web Server in Browser
Open:
http://<instance_ip>
You should see:
Welcome to Terraform + Ansible Web Server
3.3. Verify with Curl
Run:
curl http://<instance_ip>
Troubleshooting Guide – Using Ansible With Terraform
Issue | Possible Cause | Solution |
Ansible fails to connect to the server | Incorrect SSH key or missing user permissions | Ensure the correct SSH key is used and the user has proper access (chmod 600 ~/.ssh/id_rsa). |
Terraform apply fails with authentication errors | AWS credentials are missing or incorrect | Check ~/.aws/credentials or use export AWS_ACCESS_KEY_ID and export AWS_SECRET_ACCESS_KEY. |
Ansible reports “host unreachable” | Public IP not updated in the inventory file | Regenerate the inventory file using Terraform outputs. |
Packages fail to install in Ansible | apt or yum not updated | Add apt update -y or yum update -y before installing packages. |
Terraform state lost after restarting system | Using local state file instead of remote backend | Configure remote state storage in AWS S3 or Terraform Cloud. |
Ansible fails due to Python missing | Some cloud images don’t come with Python pre-installed | Add the provisioner “remote-exec” in Terraform to install Python before Ansible runs. |
Security group rules not applied | Terraform state is outdated | Run terraform refresh or terraform apply again. |
Ansible playbook hangs on SSH connection | SSH key is missing or incorrect user is used | Use ansible -i inventory.ini all -m ping -u ubuntu to test connectivity. |
Terraform apply takes too long | Large resources being created | Use a terraform plan to review changes before applying. |
Deployment works in Terraform but fails in Ansible | Instance not ready when Ansible runs | Add a wait time in Terraform before running Ansible. Example: sleep 30 && ansible-playbook setup.yml. |
Wrapping Up – Using Ansible With Terraform
Using Ansible with Terraform makes a flexible workflow for spinning up servers with software and hardware configurations. This guide will help you use Ansible with Terraform effectively for a seamless process.
Frequently Asked Questions
How do Ansible and Terraform work together?
Terraform provisions infrastructure (e.g., creating EC2 instances), and Ansible configures those instances (e.g., installing software, setting up security rules).
Can I use Ansible to manage Terraform state?
No, Terraform manages its own state files. However, Ansible can be used to execute Terraform commands within a playbook using the terraform
module.
What are the benefits of using Ansible with Terraform?
– Full automation: Terraform provisions infrastructure, and Ansible configures it.
– Scalability: Easily manage cloud resources and applications.
– Consistency: Reduce manual errors with codified infrastructure and configurations.