Execute Ansible playbooks in Terraform main.tf file

Hi,

Is there a way to execute Ansible playbooks in Terraform main.tf file? For example I want to deploy nginx webserver inside GCP GCE VM Instance using Ansible playbook once GCP GCE VM Instance is provisioned using Terraform.

Please guide. Thanks in advance.

Best Regards,

Kaushal

Hi Kausal,

Depending on the provider, you can use cloud-init to:

  • Invoke an installation of Ansible

  • Download the Ansible code

  • Run the code from a local installed instance of Ansible

  • Rilindo

Thanks Rilindo for the quick response and much appreciated. I will appreciate if you can provide me with a basic working example to understand it and I will implement it once i play around with it. Thanks in Advance.

Best Regards,

Kaushal

Hi Rilindo,

I am using Google Cloud Platform (GCP) - Google Cloud as my primary cloud service provider. Please guide. Thanks in advance.

Best Regards,

Kaushal

Hi Kaushal,

You would want to review the Terraform documentation for google_compute_instance - likely metadata_startup_script is your answer:

https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance#metadata_startup_script

Any more this goes beyond the scope of this mailing list, so I would recommend reaching to appropriate Hashicorp or GCP resources for more help.

  • Rilindo

Hi Kausal,

Depending on the provider, you can use cloud-init to:

- Invoke an installation of Ansible
- Download the Ansible code
- Run the code from a local installed instance of Ansible

- Rilindo

I've done this myself, especially to use consistent playbooks for
docker and Terraform and other virtualization tools without a shared
Ansible server. Not to *never* install the ansible package this way,
only install "ansible-core", because the ansible package is a bulky
conglomeration of roughly 100 add-on packages, none or nearly none of
which are of any use to such a micro ansible setup. Installing the
"ansible" package slows such installations quite a lot and soaks up
space not needed for a VM or docker image at all.

Nico Kadel-Garcia