サーバ構築

【terraform】workspace環境でs3にあるremote_stateから値取得する時にはまった

更新日:

事象

tfstateをs3に置いて、outputした変数を別環境で使うため下記のように設定した。

terraform {
  backend "s3" {
    bucket = "hoge-system01-terraform-tfstate"
    key    = "terraform.tfstate/VPC"
    region = "ap-northeast-1"
  }
}

output "vpc_id" {
  description = "The ID of the VPC"
  value       = "${module.vpc.vpc_id}"
}
data "terraform_remote_state" "vpc" {
  backend = "s3"

  config {
    bucket = "hoge-system01-terraform-tfstate"
    key    = "env:/${terraform.workspace}/terraform.tfstate/VPC"
    region = "ap-northeast-1"
  }
}

output "remote_output" {
  value = "${data.terraform_remote_state.vpc.vpc_id}"
}

で、 terraform plan とかすると、下記のエラーがでてremote_stateから値とれない。

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

data.terraform_remote_state.vpc: Refreshing state...

------------------------------------------------------------------------

Error: Error running plan: 1 error(s) occurred:

* output.remote_output: Resource 'data.terraform_remote_state.vpc' does not have attribute 'vpc_id' for variable 'data.terraform_remote_state.vpc.vpc_id'

原因

色々試したところ、S3のパスに : があるのがよくないっぽい。
試しに terraform_remote_state のパスを下記(env:/ > env/)のようにして、実ファイルも同じとこにおくと、エラーはでなかった。

data "terraform_remote_state" "vpc" {
  backend = "s3"

  config {
    bucket = "hoge-system01-terraform-tfstate"
    key    = "env/${terraform.workspace}/terraform.tfstate/VPC"
    region = "ap-northeast-1"
  }
}

output "remote_output" {
  value = "${data.terraform_remote_state.vpc.vpc_id}"
}

backendの設定で特に指定しなければworkspace利用時はenv:/〜にtfstateファイルが置かれるっぽい。

解決策

backendの設定に workspace_key_prefix を追加する。

terraform {
  backend "s3" {
    bucket = "hoge-system01-terraform-tfstate"
    key    = "terraform.tfstate/VPC"
    workspace_key_prefix = "env"
    region = "ap-northeast-1"
  }
}

これで、変な:が入らない。

-サーバ構築
-

Copyright© 明日から頑張ります。 , 2025 All Rights Reserved Powered by STINGER.