terraformのstate管理用にdynamodbとs3をプロビジョニングする

## どんな記事か

terraformのtfstate管理用のリソースを作成するのと格闘している記事です。
（まだ手探りでやっているので、こちらよりも公式ドキュメントを参照したほうがいいかもしれません）

## 参考

こちらを参考にさせていただきました、ありがとうございました。

https://takelg.com/terraform-tfstate_manage/


## tfstate管理用のリソース作成

ディレクトリ構成は以下のようになっています。

```
tfstate-management git:(feature/terraform) ✗ tree
.
├── backend.tf
├── provider.tf
└── variable.tf
```

リソースを`backend.tf`に書きます。

```tfstate-management/backend.tf
resource "aws_s3_bucket" "terraform-xxx-remote-state" {
    bucket = var.s3_bucket_name

    lifecycle {
        prevent_destroy = true
    }

    server_side_encryption_configuration {
        rule {
            apply_server_side_encryption_by_default {
                sse_algorithm = "AES256"
            }
        }
    }

    tags = {
        Terraform = "true"
        Name = "terraform"
    }
}

resource "aws_dynamodb_table" "terraform-xxx-state-lock" {
    name = var.dynamodb_name
    billing_mode = "PAY_PER_REQUEST"
    hash_key = "LockID"

    attribute {
        name = "LockID"
        type = "S"
    }

    tags = {
        Terraform = "true"
        Name = "terraform"
    }
}

```

provider情報を`provider.tf`に書きます。

```tfstate-management/provider.tf
provider "aws" {
    region = var.aws_region
    profile = var.aws_profile
}

terraform {
    required_providers {
      aws = {
          source = "hashicorp/aws"
          version = "~> 3.27"
      }
    }
}

```

変数を `variable.tf`に書いておきます。

```tfstate-management/variable.tf
variable "aws_region" {
    default = "ap-northeast-1"
}

variable "aws_profile" {
    type = string
    default = "default"
}

variable "s3_bucket_name" {
    type = string
    default = "terraform-xxx-remote-state"
}

variable "dynamodb_name" {
    type = string
    default = "terraform-xxx-state-lock"
}
```

初期化します。

```
terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 3.27"...
- Installing hashicorp/aws v3.60.0...
- Installed hashicorp/aws v3.60.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
```

planする。

```
terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

===== 略 =====

      + versioning {
          + enabled    = (known after apply)
          + mfa_delete = (known after apply)
        }
    }

Plan: 2 to add, 0 to change, 0 to destroy.

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
```

applyする。

```

terraform apply

===== 略 =====

Plan: 2 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_dynamodb_table.terraform-xxx-state-lock: Creating...
aws_s3_bucket.terraform-xxx-remote-state: Creating...
aws_s3_bucket.terraform-xxx-remote-state: Creation complete after 4s [id=terraform-xxx-remote-state]
aws_dynamodb_table.terraform-xxx-state-lock: Creation complete after 8s [id=terraform-xxx-state-lock]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

```

applyしたあとには `terraform.tfstate`が追加されます。

```
tfstate-management ✗ tree
.
├── backend.tf
├── provider.tf
├── terraform.tfstate
└── variable.tf
```

awsのコンソールでもリソースが確認できます。