はじめに
terraform構築したことない方は、ぜひ先にこちらも参照ください(^o^)★
tfstateとは
Terraformが管理するリソースの現在の状態を記録するファイルです。これはTerraformコマンドでリソースの反映等を行うたびに記録が上書きされます。
tfstateの保管先を定めていない場合はローカルで保管することになりますが、業務ではローカルで保管することは少ないでしょう。なので以下Amazon S3で保管するための手順を記します。
tfstateファイルをリモート保管
S3バケットを作成する
tfstateを保管するためのディレクトリとしてAmazonS3を利用します。
AWSコンソール画面からS3にて、バケットを作成します。今回は東京リージョンで作成します。
パブリックアクセスはすべてブロックにしましょう。
バケットのバージョニングはどちらでも大丈夫です。
tfstate保管先を設定
providers.tfを開き、以下を追加します。
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
# version = "~> 5.92"
}
}
+ backend "s3" {
+ bucket = "作成したバケット名"
+ region = "バケットが存在するリージョン"
+ key = "terraform.tfstate"
+ }
required_version = ">= 1.2"
}
provider "aws" {
region = "ap-northeast-1"
}
providers.tfを修正後、以下のコマンドを実施します。terraform apply
でリソース反映後、指定したS3バケットにterraform.tfstateが自動的に作成されます。
> terraform init
> terraform apply
Terraform Configurationのルートディレクトリ(main.tf等が置いてあるディレクトリ)に既にterraform.tfstateファイルが存在し、tfstateファイルのS3バケットへのコピーのみを行いたい場合はterraform init
(またはterraform init -upgrade
)を実行します。
> terraform init
Initializing the backend...
Do you want to copy existing state to the new backend?
Pre-existing state was found while migrating the previous "local" backend to the
newly configured "s3" backend. No existing state was found in the newly
configured "s3" backend. Do you want to copy this state to the new "s3"
backend? Enter "yes" to copy and "no" to start with an empty state.
Enter a value: yes
ローカルにあるterraform.tfstateをS3にコピーしますか?と聞かれるので、Enter a value: yes
と答えるとS3バケットにローカルのterraform.tfstateがコピーされます。
Appendix
関連する記事