首页 > 解决方案 > Terraform 远程后端未填充

问题描述

我是 terraform 的新手,可能不了解它应该如何工作,但是....

我正在尝试在 Google Bucket Storage 上设置远程后端。我可以看到当我在 GCS 中运行“terraform apply”时会创建一个文件,但该文件大部分是空的。在我的本地文件系统上,将使用所有正确的配置创建一个 terraform.tfstate。我希望 terraform.tfstate 将在我的 GCS 存储桶中更新,而不是在本地更新。

下面是我的设置以及文件输出在服务器上的样子。我没有包括我的本地 terraform.tfstate,因为它有一些专有的东西(但它填充了我当前的状态)。

任何帮助,将不胜感激。

主文件

variable "cluster" {}
variable "project" {}
variable "region" {}
variable "bucket" {}
variable "terraformPrefix" {}
variable "mainNodeName" {}
variable "vpcLocation" {}
variable "nodeMachineType" {}
variable "credentialsLocation" {}


data "terraform_remote_state" "foo" {
  backend = "gcs"
  config = {
    bucket = "${var.bucket}"
    prefix = "${var.terraformPrefix}"
  }
}

provider "google" {
  //This needs to be updated to wherever you put your credentials
  credentials = "${file("${var.credentialsLocation}")}"
  project     = "${var.project}"
  region      = "${var.region}"
}

resource "google_container_node_pool" "primary_pool" {
  name       = "${var.mainNodeName}"
  cluster    = "${var.cluster}"
  location   = "${var.vpcLocation}"
  node_count = "2"

  node_config {
    machine_type = "${var.nodeMachineType}"

    oauth_scopes = [
      "https://www.googleapis.com/auth/logging.write",
      "https://www.googleapis.com/auth/monitoring",
      "https://www.googleapis.com/auth/devstorage.read_only",
      "https://www.googleapis.com/auth/service.management.readonly",
      "https://www.googleapis.com/auth/servicecontrol",
      "https://www.googleapis.com/auth/trace.append",
    ]
  }

  management {
    auto_repair  = true
    auto_upgrade = true
  }
  autoscaling {
    min_node_count = 2
    max_node_count = 10
  }
}

GCS 远程后端状态:

{
    "version": 3,
    "serial": 1,
    "lineage": "760dcfe4-dee3-4875-b953-3f085439a25b",
    "modules": [
        {
            "path": [
                "root"
            ],
            "outputs": {},
            "resources": {},
            "depends_on": []
        }
    ]
}

标签: google-cloud-platformterraform

解决方案


您正在使用数据源来定义远程状态,而不是后端资源。

这样,您将只能读取您定义的远程状态,而不是写入它。

请改用后端。

例子:

terraform {
  backend "gcs" {
    bucket  = "tf-state-prod"
    prefix  = "terraform/state"
  }
}

来源:https ://www.terraform.io/docs/backends/types/gcs.html


推荐阅读