3

通过Google Cloud Storage(GCS)管理Terraform的状态State - 南瓜慢说

 1 year ago
source link: https://www.cnblogs.com/larrydpk/p/17052867.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

通过Google Cloud Storage(GCS)管理Terraform的状态State

管理Terraform状态文件的最佳方式是通过云端的统一的存储,如谷歌云就用GCS。

首先要创建一个Bucket:

$ gsutil mb -p pkslow -l us-west1 -b on gs://pkslow-terraform
Creating gs://pkslow-terraform/...

$ gsutil ls gs://
gs://pkslow-terraform/

然后在Terraform文件中配置对应的信息:

terraform {
  backend "gcs" {
    bucket  = "pkslow-terraform"
    prefix  = "state/gcp/pubsub"
  }
}

初始化后,就会在Bucket上创建对应的目录:

$ terraform init -plugin-dir=${TERRAFORM_PLUGIN}

变更生效:

$ terraform apply -auto-approve

我们在浏览器查看一下,发现已经成功状态了对应的状态文件:

946674-20230114235517766-1889281728.png

通过远程的云端,不仅可以存入状态文件,也可以从状态文件读取数据,如一些输出变量。比如模块A创建了一个VM,而我们可能通过这种方式获取它的IP,以便在其它模块使用。大致的配置如下:

data "terraform_remote_state" "foo" {
  backend = "gcs"
  config = {
    bucket  = "terraform-state"
    prefix  = "prod"
  }
}

resource "template_file" "bar" {
  template = "${greeting}"

  vars {
    greeting = "${data.terraform_remote_state.foo.greeting}"
  }
}

代码请查看GitHub: https://github.com/LarryDpk/pkslow-samples


Reference:

通过Terraform创建GCP Pubsub


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK