Terraform Backend
테라폼 state를 관리하는 원격 저장소
테라폼의 state 파일을 어디에 저장하고 가져올지에 대한 설정으로 기본적으로 로컬스토리지에 저장하지만, 설정에 따라 S3, etcd 등을 사용할 수 있다.
많은 backend type이 있지만 s3를 가장 많이 사용함
init.tf //s3, DynamoDB 생성
provider "aws" {
region = "ap-northeast-2" # Please use the default region ID
version = "~> 2.49.0" # Please choose any version or delete this line if you want the latest version
}
# S3 bucket for backend
resource "aws_s3_bucket" "tfstate" {
bucket = "tf101-jupiter-apne2-tfstate"
versioning {
enabled = true # Prevent from deleting tfstate file
}
}
# DynamoDB for terraform state lock
resource "aws_dynamodb_table" "terraform_state_lock" {
name = "terraform-lock"
hash_key = "LockID"
billing_mode = "PAY_PER_REQUEST"
attribute {
name = "LockID"
type = "S"
}
}
backend.tf //backend 설정
terraform {
backend "s3" {
bucket = "terraform-s3-bucket" # bucket 이름
key = "terraform/own-your-path/terraform.tfstate" # s3 내에서 저장되는 경로
region = "ap-northeast-2"
encrypt = true
dynamodb_table = "terraform-lock"
}
}
init.tf, backend.tf 파일 생성 후 terraform init을 하면 state 파일이 backend(s3)에 저장된다.
terraform.tfstate 파일을 지우고 plan을 해도 정상적으로 동작한다. init을 하면 state 파일을 .terraform 내부에 s3로부터 state를 받아와 저장하기 때문에 state 파일의 유무와 관계없이 동작한다.