如何用Terraform代码调用Ansible Playbook? [英] How to call ansible playbook in terraform code?

查看:158
本文介绍了如何用Terraform代码调用Ansible Playbook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个能正常工作的Ansible剧本,现在我必须使用Terrform脚本来调用该剧本.目前,我正在使用如下所示的代码,但在terraform初始化期间会导致错误:错误:未知的根级别密钥:供应商

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

我正在使用Terraform v0.11.7,并且仅在运行此特定代码时发生错误.另外,我的main.tf仅包含此代码.我使用的目录结构是:

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看起来像:

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}'"]
}

我希望应该从terraform脚本中调用该剧本,并显示结果.

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

推荐答案

以代码形式 main.tf 摘录的代码不完整.您能否发布运行 remote-exec 设置程序的完整资源定义?

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?

Ansible剧本应该怎么做?在远程主机本身上创建用户?还是仅仅是存储您的Ansible脚本的主机,而实际上是从那里在另一台远程主机上创建了用户?

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?

如@ydaetskcoR所述,您需要在 null_resource 内运行此代码:

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}'"]
  }
}

但是,我建议安装Ansible Provisioner,如上面的评论中所述.这样,您就可以将Ansible剧本直接与Terraform代码捆绑在一起,而无需连接到其他实例.

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.

这篇关于如何用Terraform代码调用Ansible Playbook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆