LoginSignup
4
2

More than 1 year has passed since last update.

tfstateがS3からダウンロードできない。

Posted at

はじめに

tfstateファイルを保存するAWSアカウント、Terraformでリソースを作成するAWSアカウントの2つのAWSアカウントでTerraform構築した際に、tfstateファイルをS3からダウンロードできないってことがありましたので、原因を記載します。
まずはじめに、Terraformでは以下のコードのようにtfstateの保存先をbackendで指定することができます。

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "3.50.0"
    }
  }
  # この部分
  backend "s3" {
    bucket = "xxxxxxxxxxxxxx"
    key = "terraform.tfstate"
    region = "xxxxxxxxxxxxxx"
    profile = "xxxxxxxxxxxxx"
  }
}

provider "aws" {
  profile = var.aws_profile
  region = var.aws_region
}

私が発生した事象

backend s3、provider awsのprofileプロパティの切り分けを行わなかったことで、tfstateを保存したアカウントと、Terraformを実行したアカウントが一緒になりました。

tfstateファイルの保存先アカウントのバケットに、Terraformでリソースを作成したアカウントでtfstateファイルを格納していました。

つまりこんな感じです。
tstateファイルを格納したバケットの権限:tfstateファイルを保存する予定だったAWSアカウント
tstateファイル(オブジェクト)の権限:Terraformでリソースを作成したアカウント

予防策

前述の通り、backendブロック、providerブロックで正しくprofile指定してあげることで、tfstate保存先アカウントでtfstateファイルをダウンロードすることができます。

つまり、以下のように記載します。

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "3.50.0"
    }
  }
  # この部分
  backend "s3" {
    bucket = "xxxxxxxxxxxxxx"
    key = "terraform.tfstate"
    region = "xxxxxxxxxxxxxx"
    # tfstate保存先アカウントの権限でtfstateファイルを格納する。
    profile = "xxxxxxxxxxxxx"
  }
}

provider "aws" {
  # AWSリソースを作成する環境と権限は、Terraformでリソースを作成するアカウントを指定する。
  profile = var.aws_profile
  region = var.aws_region
}

もし、時すでに遅しな場合

Terraformでリソースを作成したアカウントでaws cliなどでtfstateファイルをダウンロード、オブジェクトの権限変更などを検討してみてください。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2