LoginSignup
4
5

More than 5 years have passed since last update.

TerraformのbackendでS3を使う

Posted at

"terraform.tfstate"ファイルをS3に設置する手順

バージョン情報

Terraform v0.11.13

手順

S3バケットを作成する

マネジメントコンソールから作成する(作り方はなんでもいい)。Bucket Versioningの有効化は公式が推奨しているためやっておく。

DynamoDB を作成する(必須ではない)

S3バケットを複数人同時に編集しないように、DynamoDBを作成する。
これも、マネジメントコンソールからすぐに作れる。
この時、プライマリキーを必ず"LockID"にしなければいけないことに注意。

Configurationファイルにbackend情報を記入する

下記の設定ファイルは、設定ファイルと認証情報ファイルがすでに完了していることを前提としている。

provider "aws" {
  region = "ap-northeast-1"
}

terraform {
  backend "s3" {
    bucket = "S3バケット名"               # 適宜変更
    key = "terraform.tfstate"
    encrypt = true                       # 適宜変更
    region = "ap-northeast-1"            # 適宜変更
    dynamodb_table = "DynamoDBテーブル名"  # 適宜変更
  }
}

...

Backendの設定反映

$ terraform init

ハマったところ

backendの設定に変数を使っていると、こんなエラーがでる。どうやら、backend設定の部分は変数展開の前に読み込まれるらしい。今のところどうにもならないっぽい

$ terraform init                                      

Initializing the backend...                                                                                                                         
Error loading backend config: 1 error(s) occurred:       

* terraform.backend: configuration cannot contain interpolations                                                                                    

The backend configuration is loaded by Terraform extremely early, before     
the core of Terraform can be initialized. This is necessary because the backend
dictates the behavior of that core. The core is what handles interpolation
processing. Because of this, interpolations cannot be used in backend    
configuration.                                                                 

If you'd like to parameterize backend configuration, we recommend using                             
partial configuration with the "-backend-config" flag to "terraform init".
4
5
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
5