在 Terraform 0.9 中从远程状态迁移到后端

Migrating from remote-state to backend in Terraform 0.9

我下载了 terraform 0.9 并尝试按照 migration guideremote-state 移动到 backend

不过好像不行。我替换了:

data "terraform_remote_state" "state" {
  backend = "s3"
  config {
    bucket = "terraform-state-${var.environment}"
    key = "network/terraform.tfstate"
    region = "${var.aws_region}"
  }
}

terraform {
  backend "s3" {
    bucket = "terraform-backend"
    key = "network/terraform.tfstate"
    region = "us-west-2"
  }
}

然而,当我 运行 terraform 在我的环境文件夹之一中初始化时,我得到:

Deprecation warning: This environment is configured to use legacy remote state. Remote state changed significantly in Terraform 0.9. Please update your remote state configuration to use the new 'backend' settings. For now, Terraform will continue to use your existing settings. Legacy remote state support will be removed in Terraform 0.11.

You can find a guide for upgrading here:

https://www.terraform.io/docs/backends/legacy-0-8.html

我还不得不放弃变量插值,因为这不再被允许了。这是否意味着一个 S3 Bucket 用于多个环境?我在这里错过了什么?

根据升级指南 (https://www.terraform.io/docs/backends/legacy-0-8.html),在 terraform init 之后,您还必须 运行 terraform plan 完成迁移,这将在 s3 更新远程状态文件。

至于针对多个环境的配置,我们最终使用包装器 shell 脚本为 ${application_name}/${env}/${project} 传入参数,并使用部分配置。

对于这样的项目结构:

├── projects
│   └── application-name
│       ├── dev
│       │   ├── bastion
│       │   ├── db
│       │   ├── vpc
│       │   └── web-cluster
│       ├── prod
│       │   ├── bastion
│       │   ├── db
│       │   ├── vpc
│       │   └── web-cluster
│       └── backend.config
└── run-tf.sh

对于每个 application_name/env/component = 文件夹(即 dev/vpc),我们添加了一个占位符后端配置文件,如下所示: backend.tf:

terraform {
    backend "s3" {
    }
}

每个组件的文件夹内容如下所示:

│       ├── prod
│       │   ├── vpc
│       │   │   ├── backend.tf
│       │   │   ├── main.tf
│       │   │   ├── outputs.tf
│       │   │   └── variables.tf

在 "application_name/" 或 "application_name/env" 级别,我们添加了一个 backend.config 文件,如下所示:

bucket     = "BUCKET_NAME"
region     = "region_name"
lock       = true
lock_table = "lock_table_name"
encrypt    = true

我们的包装器 shell 脚本需要参数 application-nameenvironmentcomponent 和实际地形 cmd 到 运行。

运行-tf.sh脚本内容(简体):

#!/bin/bash

application=
envir=
component=
cmd=

tf_backend_config="root_path/$application/$envir/$component/backend.config"

terraform init -backend=true -backend-config="$tf_backend_config" -backend-config="key=tfstate/${application}/${envir}/${component}.json" 

terraform get

terraform $cmd

这是典型的 运行-tf.sh 调用的样子:

$ run-tf.sh application_name dev vpc plan

$ run-tf.sh application_name prod bastion apply

您对带有远程状态的 terraform 远程命令感到困惑。您不必更改 tf 文件中的任何远程状态内容。

不要使用 terraform 远程命令配置远程状态,而是使用迁移中提到的后端配置文件 link。

请参阅此 link 中的第二条 github 评论。关于他为迁移所做的工作,它有很好的分步程序。 https://github.com/hashicorp/terraform/issues/12792