Different solutions exist to run Terraform, and them ansible:
- Using Terraform Output as Ansible Inventory :
https://github.com/adammck/terraform-inventory
$ terraform-inventory -inventory terraform.tfstate [all] 10.10.1.2 10.10.1.3 - `local-exec` / `remote-exec` : terraform runs ansible locally
``` provisioner "local-exec" {command = "ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -u {var.user} -i '${self.ipv4_address},' --private-key ${var.ssh_private_key} playbook.yml"} ```key component here is the ${self.ipv4_address} variable. After provisioning the machine, Terraform knows its IP address. And we need to pass an IP address for Ansible.
(cf https://www.cprime.com/resources/blog/terraform-and-ansible-tutorial-integrating-terraform-managed-instances-with-ansible-control-nodes )
using dynamic inventory and cloud providers specific ansible modules
- AWS : https://docs.ansible.com/ansible/latest/collections/amazon/aws/aws_ec2_inventory.html
- GCP : https://docs.ansible.com/ansible/latest/collections/google/cloud/gcp_compute_inventory.html#ansible-collections-google-cloud-gcp-compute-inventory and so on...
AWS example of the dynamic inventory:
inventory=./aws_ec2.yml
ansible <group-name> -i aws_ec2.yaml -m ping --private-key=<private-key-name>
ansible-playbook myplaybook.yml