如何将 terraform 输出变量作为 vars_files 传递给 ansible? [英] How to pass terraform outputs variables into ansible as vars_files?
问题描述
我正在使用 terraform 配置 AWS 基础设施,并希望使用 vars_file
将诸如 aws_subnet_id
和 aws_security_id
之类的变量传递到 ansible playbook(不要知道是否还有其他方法).我该怎么做?
I am provisioning AWS infrastructure using terraform and want to pass variables such as aws_subnet_id
and aws_security_id
into ansible playbook using vars_file
(don't know if there is any other way though). How can I do that?
推荐答案
我使用 Terraform local_file
创建 Ansible vars_file.我在变量名前添加了一个 tf_
前缀,以表明它们源自 Terraform:
I use Terraform local_file
to create an Ansible vars_file. I add a tf_
prefix to the variable names to make it clear that they originate in Terraform:
# Export Terraform variable values to an Ansible var_file
resource "local_file" "tf_ansible_vars_file_new" {
content = <<-DOC
# Ansible vars_file containing variable values from Terraform.
# Generated by Terraform mgmt configuration.
tf_environment: ${var.environment}
tf_gitlab_backup_bucket_name: ${aws_s3_bucket.gitlab_backup.bucket}
DOC
filename = "./tf_ansible_vars_file.yml"
}
运行 terraform apply
以创建包含 Terraform 变量值的 Ansible var_file tf_ansible_vars_file.yml
:
Run terraform apply
to create Ansible var_file tf_ansible_vars_file.yml
containing Terraform variable values:
# Ansible vars_file containing variable values from Terraform.
# Generated by Terraform mgmt configuration.
tf_environment: "mgmt"
tf_gitlab_backup_bucket_name: "project-mgmt-gitlab-backup"
将 tf_ansible_vars_file.yml
添加到您的 Ansible 手册:
Add tf_ansible_vars_file.yml
to your Ansible playbook:
vars_files:
- ../terraform/mgmt/tf_ansible_vars_file.yml
现在,在 Ansible 中,此文件中定义的变量将包含来自 Terraform 的值.
Now, in Ansible the variables defined in this file will contain values from Terraform.
显然,这意味着您必须在 Ansible 之前运行 Terraform.但是对于您的所有 Ansible 用户来说,它不会那么明显.将断言添加到您的 Ansible 剧本中,以帮助用户找出在 tf_
变量缺失时该怎么做:
Obviously, this means that you must run Terraform before Ansible. But it won't be so obvious to all your Ansible users. Add assertions to your Ansible playbook to help the user figure out what to do if a tf_
variable is missing:
- name: Check mandatory variables imported from Terraform
assert:
that:
- tf_environment is defined
- tf_gitlab_backup_bucket_name is defined
fail_msg: "tf_* variable usually defined in '../terraform/mgmt/tf_ansible_vars_file.yml' is missing"
更新:此答案的早期版本使用了 Terraform 模板.经验表明,模板文件容易出错并增加了不必要的复杂性.所以我把模板文件移到了local_file
的content
.
UPDATE: An earlier version of this answer used a Terraform template. Experience shows that the template file is error prone and adds unnecessarily complexity. So I moved the template file to the content
of the local_file
.
这篇关于如何将 terraform 输出变量作为 vars_files 传递给 ansible?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!