How to call ansible playbook in terraform code?

强颜欢笑 提交于 2021-01-27 17:35:34

问题


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.


回答1:


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:

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 won't not need to connect to some other instance.



来源:https://stackoverflow.com/questions/56315955/how-to-call-ansible-playbook-in-terraform-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!