Cloudflare R2をTerraformで管理してTerraformに入門してみる

2023.07.07

どうも、オペレーション部の西村祐二です。

7月7日は創立記念日ということで、今まで触ったことのなかった新しいことをはじめてみようと思います。

今までCloudFormationやCDKが主でTerraformを触ったことなかったので、Terraformに入門してみたいと思います。

今回、Cloudflare R2というS3互換オブジェクトストレージのサービスがあり、それをTerraformで管理してみたいと思います。

やってみる

Cloudflareのチュートリアルのページを参考に実施していきたいと思います。

Terraformで操作できるリソースの情報などはTerraformのサイトから確認できます。

前提条件

Cloudflareのアカウントは取得されており、Webサイトの設定などが完了している前提で進めていきます。

Terraformの環境整備

まずは、Terraformの環境を整えていきます。

Terraform自体のバージョン管理のためにtfenvを導入します。

$ brew install tfenv

今回、1.5.2を利用します

$ tfenv install 1.5.2

useコマンドを実行すると指定したバージョンでTerraformを利用できるようになります。

$ tfenv use 1.5.2

CloudflareのAPIトークンを取得

Cloudflareのコンソールにアクセスし、マイプロフィールを開きます。APIトークンという項目があるのでクリックし、「トークンを作成する」ボタンをクリックします。

テンプレートにR2だけ操作するテンプレートが見当たらなかったので、「カスタム トークンを作成する」のボタンをクリックします。

今回は「test-Terraform-R2」という名前に設定しています。適宜変更してください。

アクセス許可のところを「Workers R2 Storage」「編集」に設定します。

アカウントリソースのところも適宜変更してください。今回はデフォルトの「すべてのアカウント」のままにしています。

「概要に進む」をクリックし、APIトークンを作成し、生成されたトークンを控えておきます。

CloudflareのアカウントID、Zone IDを取得

Cloudflareのコンソールにある Webサイトにあるドメインをクリックし、右下の欄から取得することができます。

Terraformのファイルを作成

ここからTerraformの話になります。

cloudflare.tfというファイルを作成します。

プロバイダーの情報、取得したAPIトークン、Zone ID、アカウントIDを設定します。

最後に今回管理したい、R2のリソース設定を記載します。

他にどんなリソースが管理できるかはTerraformのサイトから確認できます。

cloudflare.tf

terraform {
  required_providers {
    cloudflare = {
      source = "cloudflare/cloudflare"
      version = "~> 4"
    }
  }
}

provider "cloudflare" {
  api_token = "<your api token>"
}

variable "zone_id" {
  default = "<your zone id>"
}


variable "account_id" {
  default = "<your account id>"
}

resource "cloudflare_r2_bucket" "example" {
  account_id = var.account_id
  name       = "terraform-test-bucket"
}

initコマンドを実行して初期化します。

$ terraform init                

Initializing the backend...

Initializing provider plugins...
- Finding cloudflare/cloudflare versions matching "~> 4.0"...
- Installing cloudflare/cloudflare v4.9.0...
- Installed cloudflare/cloudflare v4.9.0 (self-signed, key ID xxxxxxxxx)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html

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.

ローカルに

.terraform

フォルダなどが作成されます。

実行内容の確認

plan

のサブコマンドを実行するとDryRunを実行してくれて、実行内容を確認することができます。

実行内容が見やすく、どのような実行がされるのか把握しやすくていいですね。

$ 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:

  # cloudflare_r2_bucket.example will be created
  + resource "cloudflare_r2_bucket" "example" {
      + account_id = "<your account id>"
      + id         = (known after apply)
      + location   = (known after apply)
      + name       = "terraform-test-bucket"
    }

Plan: 1 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を実行すると、DryRunで確認した変更内容が実施されます。

--auto-approveのオプションをしているすることで確認のステップをスキップすることができます。

$ terraform apply --auto-approve

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:

  # cloudflare_r2_bucket.example will be created
  + resource "cloudflare_r2_bucket" "example" {
      + account_id = "<your account id>"
      + id         = (known after apply)
      + location   = (known after apply)
      + name       = "terraform-test-bucket"
    }

Plan: 1 to add, 0 to change, 0 to destroy.
cloudflare_r2_bucket.example: Creating...
cloudflare_r2_bucket.example: Creation complete after 3s [id=terraform-test-bucket]

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

Cloudflareのコンソール画面を確認すると想定どおり、R2のバケットが作成されていることがわかります。

showコマンドでも確認することができます。

$ terraform show                
# cloudflare_r2_bucket.example:
resource "cloudflare_r2_bucket" "example" {
    account_id = "<your account id>"
    id         = "terraform-test-bucket"
    location   = "ENAM"
    name       = "terraform-test-bucket"
}

リソース更新

バケット名を「terraform-test-buckets」に変更して、planを実行して、内容を確認してみます。

削除された後に再作成される旨の表示がされていることがわかります。

きちんとどういう操作が行われるか表示されていいですね。

$ terraform plan                
cloudflare_r2_bucket.example: Refreshing state... [id=terraform-test-bucket]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # cloudflare_r2_bucket.example must be replaced
-/+ resource "cloudflare_r2_bucket" "example" {
      ~ id         = "terraform-test-bucket" -> (known after apply)
      ~ location   = "ENAM" # forces replacement -> (known after apply) # forces replacement
      ~ name       = "terraform-test-bucket" -> "terraform-test-buckets" # forces replacement
        # (1 unchanged attribute hidden)
    }

Plan: 1 to add, 0 to change, 1 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 --auto-approve
cloudflare_r2_bucket.example: Refreshing state... [id=terraform-test-bucket]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # cloudflare_r2_bucket.example must be replaced
-/+ resource "cloudflare_r2_bucket" "example" {
      ~ id         = "terraform-test-bucket" -> (known after apply)
      ~ location   = "ENAM" # forces replacement -> (known after apply) # forces replacement
      ~ name       = "terraform-test-bucket" -> "terraform-test-buckets" # forces replacement
        # (1 unchanged attribute hidden)
    }

Plan: 1 to add, 0 to change, 1 to destroy.
cloudflare_r2_bucket.example: Destroying... [id=terraform-test-bucket]
cloudflare_r2_bucket.example: Destruction complete after 1s
cloudflare_r2_bucket.example: Creating...
cloudflare_r2_bucket.example: Creation complete after 3s [id=terraform-test-buckets]

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

リソース削除

最後にリソースを削除したいと思います。

destroyコマンドで作成したリソースを削除することができます。

途中で入力が求められyesと入力することで実施されます。

$ terraform destroy                   
cloudflare_r2_bucket.example: Refreshing state... [id=terraform-test-buckets]

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

Terraform will perform the following actions:

  # cloudflare_r2_bucket.example will be destroyed
  - resource "cloudflare_r2_bucket" "example" {
      - account_id = "<your account id>" -> null
      - id         = "terraform-test-buckets" -> null
      - location   = "APAC" -> null
      - name       = "terraform-test-buckets" -> null
    }

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

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

cloudflare_r2_bucket.example: Destroying... [id=terraform-test-buckets]
cloudflare_r2_bucket.example: Destruction complete after 1s

Destroy complete! Resources: 1 destroyed.

さいごに

今回、Cloudflare R2をTerraformで管理してみました。

はじめてTerraformを触ったのですが、実施内容の確認ができたり、表示もとてもわかりやすく、ハマることもなく利用体験がとても良かったです。

今後、積極的に利用していきたいと思います。

次はCloudflare上のリソースをHCL化し、出力されたソースを利用してTerraformのState管理下にすることができるcf-terraformingを触ってみようと思います。

誰かの参考になれば幸いです。

参考サイト

Cloudflare の DNS を Terraform で管理してみた