ansibleterraformprovisioning

How to call ansible playbook in terraform code?


I have an ansible playbook which works well , now I have to call that playbook using terrform scripts. Currently I m using code which is shown below but it results in error during terraform init as: Error: Unknown root level key: provisioner

I am using Terraform v0.11.7 and the error occurs only when I run this specific code. Also my main.tf consists of only this code. The directory structure I have used is such as :

.
├── create-user.yml
├── library
│   └── mkpassword.py
├── main.tf
├── outputs.tf
├── roles
│   └── linux_user_creation
│       └── tasks
│           └── main.yml
└── variables.tf

main.tf looks like :

  provisioner "remote-exec" {
  inline = ["sudo dnf -y install python"]

  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = "${file(var.ssh_keyname)}"
  }
}

provisioner "remote-exec" {
  command = ["ansible-playbook -u root --private-key ${var.ssh_keyname} -i ${self.ipv4_address} create-user.yml -e 'email_id=${var.email_id}'"]
}

I expect the playbook should be called from the terraform scripts and should display the results.


Solution

  • The code snipped form main.tf is not complete. Could you post the full resource definitions in which you run the remote-exec provisioners please?

    An what should the Ansible playbook do? Create a user on the remote host itself? Or is it just a host where your Ansible scripts are stored, and the user is actually created on another remote host from there?

    As @ydaetskcoR mentioned, you need to run this code within a null_resource:

    resource null_resource "provisioner" {
      connection {
        ... # set the connection parameters here
      }
    
      provisioner "remote-exec" {
        command = ["ansible-playbook -u root --private-key ${var.ssh_keyname} -i ${self.ipv4_address} create-user.yml -e 'email_id=${var.email_id}'"]
      }
    }
    

    I'd however suggest to install the Ansible provisioner, as already mentioned in the comment above. This way you'd bundle the Ansible playbook directly with your Terraform code and do not need to connect to some other instance.