Create Ansible provisioner
Problem
I'd like to use Terraform to build infrastructure then configure it with Ansible, similar to the Chef provisioner.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Implement Ansible Provisioner in Terraform
Terraform does not natively support Ansible as a provisioner like it does with Chef. This requires a custom implementation to integrate Ansible playbooks into the Terraform workflow for configuration management after infrastructure provisioning.
Awaiting Verification
Be the first to verify this fix
- 1
Install Ansible
Ensure that Ansible is installed on the machine where Terraform is being executed. This is necessary for Terraform to invoke Ansible playbooks.
bashsudo apt-get install ansible - 2
Create Ansible Playbook
Write an Ansible playbook that defines the configuration you want to apply to your provisioned infrastructure. Save this file as 'playbook.yml'.
yaml--- - hosts: all tasks: - name: Install nginx apt: name: nginx state: present - 3
Add Local-Exec Provisioner in Terraform
Modify your Terraform configuration to include a local-exec provisioner that runs the Ansible playbook after the infrastructure is created.
hclresource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" provisioner "local-exec" { command = "ansible-playbook -i '${self.public_ip},' playbook.yml" } } - 4
Run Terraform Apply
Execute the Terraform apply command to provision the infrastructure and apply the Ansible configuration. This will create the resources and run the Ansible playbook as specified.
bashterraform apply - 5
Verify Ansible Configuration
Check the provisioned infrastructure to ensure that the Ansible playbook has been executed successfully. You can verify by checking if the intended services (e.g., nginx) are running.
bashcurl http://<instance_public_ip>
Validation
Confirm that the Ansible playbook has successfully configured the infrastructure by checking the status of the services or configurations applied. For example, if nginx was installed, you should be able to access it via a web browser or curl command.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep