使用 Terraform_remote_state 可以引用外部的 state 文件
用例
terraform workspace の切り替えなどのstateファイルが分かれているケースで、別のworkspace(stateファイル)からそのworkspaceのリソース情報を参照したい時などに terraform_rempte_state dataリソースが活用できます
本ページではGCP BigqueryのView情報を別workspaceから参照するケースで手順記載しています
环境
-
- terraform version 1.0.3
-
- state file backend -> GCS (GCP)
- Linux 3.10.0-1160.66.1.el7.x86_64 (GCE instance)
构成
Note: In Chinese, “构成” has multiple meanings depending on the context. It can mean “to constitute,” “to form,” “to compose,” or “to comprise.” Without any context, it is difficult to provide an accurate paraphrase.

步驟
在terraform工作区stg中,我们将输出要从prod引用的资源信息(value)。
output "project_id" {
value = "${google_bigquery_table.billing_view[0].project}"
}
output "table_id" {
value = "${google_bigquery_table.billing_view[0].table_id}"
}
output "dataset_id" {
value = "${google_bigquery_dataset.billing[0].dataset_id}"
}
→ 在上述中进行terraform apply (stg)。
(1) 输出了 stg 资源信息的 terraform workspace prd 端,将使用 terraform_remote_state 数据资源将其快照到 prd state 文件中。
data "terraform_remote_state" "billing" {
backend = "gcs"
workspace = "stg"
config = {
bucket = "test-backend"
prefix = "state/bigquery"
}
}
用Terraform应用于上述的(prd)环境。
以下是将stg资源信息(outputs)记录在prd.tfstate文件中的方法。
{
"version": 4,
"terraform_version": "1.0.3",
"serial": 70,
"lineage": "***",
,
{
"mode": "data",
"type": "terraform_remote_state",
"name": "billing",
"provider": "provider[\"terraform.io/builtin/terraform\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"backend": "gcs",
"config": {
"value": {
"bucket": "test-backend",
"prefix": "state/bigquery"
},
"type": [
"object",
{
"bucket": "string",
"prefix": "string"
}
]
},
"defaults": null,
"outputs": {
"value": {
"dataset_id": "billing",
"project_id": "test-project",
"table_id": "billing_view"
},
"type": [
"object",
{
"dataset_id": "string",
"project_id": "string",
"table_id": "string"
}
]
},
"workspace": "stg"
},
"sensitive_attributes": []
}
]
},
(3) 将获取到的stg资源信息(terraform_remote_state)在prd端的terraform资源中使用。
在下面的代码中,我们获取了stg项目的project_id、dataset_id和table_id信息的value,并对google_bigquery_dataset_access terraform资源的view block进行了定义。
resource "google_bigquery_dataset_access" "billing_access" {
count = local.count.billing_access[terraform.workspace]
dataset_id = google_bigquery_dataset.billing[0].dataset_id
view {
project_id = "${data.terraform_remote_state.billing.outputs.project_id}"
dataset_id = "${data.terraform_remote_state.billing.outputs.dataset_id}"
table_id = "${data.terraform_remote_state.billing.outputs.table_id}"
}
}
→使用上述命令进行 Terraform apply(prd)。
※ 在Terraform版本小于等于0.11时,无需使用.outputs(请参考官方文档)。
以上
请参考该链接
- (公式) https://www.terraform.io/language/state/remote-state-data