Creating a project that integrates Terraform and Ansible can be a great way to automate both the provisioning and configuration of infrastructure.
Project Overview
- Terraform: Used to provision an EC2 instance in AWS.
- Ansible: Used to configure the EC2 instance by installing and setting up a web server (e.g., Apache).
Step 1: Provisioning Infrastructure with Terraform
1.1. Terraform Configuration
Create a main.tf file in the terraform/ directory:
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
key_name = var.key_name
tags = {
Name = "WebServer"
}
}
output "web_server_ip" {
value = aws_instance.web.public_ip
}
1.2. Variables
Create a variables.tf file to define variables:
variable "key_name" {
description = "The name of the SSH key pair"
type = string
}
1.3. Terraform Variables File
Create a terraform.tfvars file to set values for the variables:
key_name = "your-aws-key-name"
1.4. Output the Ansible Inventory
Create an outputs.tf file to generate the Ansible inventory:
output "ansible_inventory" {
value = templatefile("inventory.tpl", {
ip = aws_instance.web.public_ip
})
}
1.5. Inventory Template
Create an inventory.tpl file to format the inventory:
[web]
${ip} ansible_ssh_user=ec2-user ansible_ssh_private_key_file=~/.ssh/your-aws-key.pem
1.6. Initialize and Apply Terraform
Run the following commands in the terraform/ directory:
terraform init
terraform apply -auto-approve
This will create an EC2 instance and output an Ansible inventory file.
Step 2: Configuring Infrastructure with Ansible
2.1. Ansible Configuration
Create an ansible.cfg file to specify settings:
[defaults]
inventory = ../terraform/terraform.tfstate.d/ansible_inventory
host_key_checking = False
2.2. Ansible Playbook
Create a playbook.yml file to define the tasks:
- hosts: web
become: yes
tasks:
- name: Update and install Apache
yum:
name: httpd
state: present
- name: Start Apache service
service:
name: httpd
state: started
enabled: yes
Step 3: Running the Ansible Playbook
Run the Ansible playbook from the ansible/ directory:
ansible-playbook playbook.yml
This playbook will connect to the EC2 instance provisioned by Terraform and install and start the Apache web server.
Step 4: Verification
- After running the playbook, you can access the public IP of the EC2 instance (output by Terraform) in your web browser. If everything was successful, you should see the Apache default page.
Step 5: Clean Up
When you are done with the project, you can destroy the resources with Terraform:
cd ../terraform
terraform destroy -auto-approve
Thank you for reading