首页 > 解决方案 > 如何使用 ansible 角色生成 terraform 执行计划?

问题描述

ansible 提供的 Terraform 模块非常适合使用 S3 后端配置为 statefile 创建 aws 资源。但无法terraform plan使用此模块获得输出。我们希望输出应该列出如下内容: Plan: 1 to add, 0 to change, 0 to destroy. 并提供要创建/销毁/更改的资源的详细信息

已在 ansible 中尝试过以下任务,但无法按预期生成输出。

以下是创建计划的 ansible 任务:

- name: "create file"
  shell: "touch {{playbook_dir}}/tfplan && ls -larth ../terraform/{{role_name}} "

- name: "Run terraform project with plan file"
  terraform:
    state: planned
    backend_config:
      bucket: "{{bootstrap_prefix}}-{{aws_account_type}}-{{caller_facts.account}}"
      region: "{{ bootstrap_aws_region }}"
      kms_key_id: "{{ kms_id.stdout }}"
      encrypt: true
      workspace_key_prefix: "{{ app_parent }}-{{ app_name }}"
      key: "terraform.tfstate"
    force_init: true
    project_path: "../terraform/{{role_name}}"
    plan_file: "{{playbook_dir}}/tfplan"
    variables:
      app_name: "{{ app_name }}"
    workspace: "{{ app_env }}"

上述ansible任务的输出:

ok: [localhost] => {
    "changed": false,
    "command": "/usr/local/bin/terraform -lock=true /root/project/ansible/tfplan",
    "invocation": {
        "module_args": {
            "backend_config": {
                "bucket": "XXXXXXXX2440728499",
                "encrypt": true,
                "key": "terraform.tfstate",
                "kms_key_id": "XXXXXXXX",
                "region": "XXXXXXXX",
                "workspace_key_prefix": "XXXXXX"
            },
            "binary_path": null,
            "force_init": true,
            "lock": true,
            "lock_timeout": null,
            "plan_file": "/root/project/ansible/tfplan",
            "project_path": "../terraform/applications",
            "purge_workspace": false,
            "state": "planned",
            "state_file": null,
            "targets": [],
            "variables": {
                "app_name": "application"

            },
            "variables_file": null,
            "workspace": "uat"
        }
    },
    "outputs": {},
    "state": "planned",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "",
    "stdout_lines": [],
    "workspace": "uat"
}

它适用于state: present( terraform apply) ,但希望它适用于state:planned( terraform plan)

标签: ansibleterraform

解决方案


当前的 ansible 文档中:To just run a terraform plan, use check mode.

此外,您应该添加到terraform模块参数:

- name: "Run terraform project with plan file"
  terraform:
    state: planned
    check_mode: true

推荐阅读