如何将terraform输出变量作为vars_files传递给ansible? [英] How to pass terraform outputs variables into ansible as vars_files?

查看:240
本文介绍了如何将terraform输出变量作为vars_files传递给ansible?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用terraform来配置AWS基础设施,并希望使用vars_file将诸如aws_subnet_idaws_security_id之类的变量传递到可播放的剧本中(不过不知道是否还有其他方法).我该怎么办?

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_filecontent.

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屋!

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