Ansible With Terraform – A Beginner Guide To Automating Infrastructure 

Ansible with terraform

Table of Contents

Get up to 50% off now

Become a partner with CyberPanel and gain access to an incredible offer of up to 50% off on CyberPanel add-ons. Plus, as a partner, you’ll also benefit from comprehensive marketing support and a whole lot more. Join us on this journey today!

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:

Tech Delivered to Your Inbox!

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.

FeatureTerraformAnsible
PurposeInfrastructure provisioningConfiguration management & automation
ExecutionDeclarative (desired state)Procedural (step-by-step tasks)
State ManagementUses state filesDoes not maintain state
Primary Use CaseCreating and managing infrastructureConfiguring software and maintaining systems
ExamplesCreating an AWS EC2 instanceInstalling 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. 

  1. Multi-Cloud Infrastructure Management
  2. Automated Environment Setup
  3. Infrastructure as Code with Continuous Deployment
  4. Scaling and Upgrading Infrastructure
  5. 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  

Enhance Your CyerPanel Experience Today!
Discover a world of enhanced features and show your support for our ongoing development with CyberPanel add-ons. Elevate your experience today!

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: 

  1. Using Terraform to provision an AWS EC2 instance.
  2. Using Ansible to install and configure an Nginx web server.
  3. 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 

IssuePossible CauseSolution
Ansible fails to connect to the serverIncorrect SSH key or missing user permissionsEnsure the correct SSH key is used and the user has proper access (chmod 600 ~/.ssh/id_rsa).
Terraform apply fails with authentication errorsAWS credentials are missing or incorrectCheck ~/.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 fileRegenerate the inventory file using Terraform outputs.
Packages fail to install in Ansibleapt or yum not updatedAdd apt update -y or yum update -y before installing packages.
Terraform state lost after restarting systemUsing local state file instead of remote backendConfigure remote state storage in AWS S3 or Terraform Cloud.
Ansible fails due to Python missingSome cloud images don’t come with Python pre-installedAdd the provisioner “remote-exec” in Terraform to install Python before Ansible runs.
Security group rules not appliedTerraform state is outdatedRun terraform refresh or terraform apply again.
Ansible playbook hangs on SSH connectionSSH key is missing or incorrect user is usedUse ansible -i inventory.ini all -m ping -u ubuntu to test connectivity.
Terraform apply takes too longLarge resources being createdUse a terraform plan to review changes before applying.
Deployment works in Terraform but fails in AnsibleInstance not ready when Ansible runsAdd 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.

Marium Fahim
Hi! I am Marium, and I am a full-time content marketer fueled by an iced coffee. I mainly write about tech, and I absolutely love doing opinion-based pieces. Hit me up at [email protected].
Unlock Benefits

Become a Community Member

SIMPLIFY SETUP, MAXIMIZE EFFICIENCY!
Setting up CyberPanel is a breeze. We’ll handle the installation so you can concentrate on your website. Start now for a secure, stable, and blazing-fast performance!