🪣

terraform入門: 環境構築 + AWS S3作ってみる(´・ω・`)

2023/06/26に公開

terraform入門: 環境構築 + AWS S3作ってみる(´・ω・`)

久しぶりにterraform触ったので手順などをメモしておく。ちなみにAWS環境触るのほぼ初(GCP派なので)(´・ω・`)

TL;DR

この記事で以下がわかります。

  • terraformセットアップ
    • terraformのインストール(※ tfenv を使用)
  • 新規プロジェクトの作成・初期化(terraform init
  • terraformで実行計画(いわゆるdry-run)確認(terraform plan) と実行(terraform apply)ができる
  • terraformでAWS S3の新規作成ができる(※ aws_s3_bucket というterraformリソースを作成)

公式なAWSチュートリアルは Terraform Get Started - AWS を見た方がよいです。

事前要件

↓ 以下が環境情報

$ aws --version     
aws-cli/2.12.1 Python/3.11.4 Darwin/21.6.0 source/arm64 prompt/off
$ aws configure list
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                <not set>             None    None
access_key     ****************xxxx shared-credentials-file    
secret_key     ****************xxxx shared-credentials-file    
    region                us-east-1      config-file    ~/.aws/config

AWS S3作ってみる

terraformセットアップ

terraformのインストール・バージョン管理用にまずはtfenvをインストールする

$ brew install tfenv
$ tfenv --version
tfenv 3.0.0

terraform 1.5.1バージョンを指定してインストール

$ tfenv install 1.5.1
$ terraform --version
Terraform v1.5.1

新規プロジェクトの作成・初期化

sample用ディレクトリを作成

mkdir hello-terraform-aws-s3
cd hello-terraform-aws-s3

main.tf を空で作成(ファイル名は *.tf であれば何でもよいが、わかりやすさのために main.tf という名前にしている)

$ touch main.tf

main.tf の中身を記述(※AWS用)

terraform {
  // terraformのバージョンを指定
  required_version = ">= 1.5.1"

  // awsプロバイダーのバージョンを指定
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }
}

// awsプロバイダーの設定
provider "aws" {
  // regionを指定
  region = "us-east-1"
}

初期化(※最初1回だけ実行)

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 4.16"...
- Installing hashicorp/aws v4.67.0...
- Installed hashicorp/aws v4.67.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.

dry-run実行で計画(plan)の確認

試しにs3バケットを作成してみる

main.tf の末尾に以下を追記

// s3バケットを作成
resource "aws_s3_bucket" "sample" {
  bucket = "sample-bucket-[your name]" // s3バケット名をユニークにするために自分の名前など入れる
  // i.e. bucket = "sample-bucket-yukinagae"
}

実際に実行する前にどのような変更計画か確認(いわゆるdry-run)

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

  # aws_s3_bucket.sample will be created
  + resource "aws_s3_bucket" "sample" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "sample-bucket-[your name]"
      + bucket_domain_name          = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = (known after apply)
      + request_payer               = (known after apply)
      + tags_all                    = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)
    }

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.

一つひとつ計画結果を見てみる

  • create(新規作成) であることがわかる(※以下3パターンある)
    • create: 新規作成
    • update-in-place: 更新
    • destroy: 削除
  • 注意: update-in-place で更新しようとしたつもりでも、 destroy → create で再作成が計画されていることもあるので、ちゃんと計画を見ることが大事。もちろんリソースによっては更新できず常に再作成になってしまう場合もあります。
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create
  • 以下のようなresource(S3)が1つ新規作成されることがわかる
    • gitの差分のように +- で表現される
Terraform will perform the following actions:

  # aws_s3_bucket.sample will be created
  + resource "aws_s3_bucket" "sample" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "sample-bucket-[your name]"
      + bucket_domain_name          = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = (known after apply)
      + request_payer               = (known after apply)
      + tags_all                    = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)
    }

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

適用(apply)

実際に適用してみる( terraform plan とほぼ同様の内容だが、最後に確認用のプロンプトが表示されるので yes と入力して実行する)

$ terraform apply

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:

  # aws_s3_bucket.sample will be created
  + resource "aws_s3_bucket" "sample" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "sample-bucket-yukinagae"
      + bucket_domain_name          = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = (known after apply)
      + request_payer               = (known after apply)
      + tags_all                    = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)
    }

Plan: 1 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 // ← ここで `yes` と入力

aws_s3_bucket.sample: Creating...
aws_s3_bucket.sample: Creation complete after 4s [id=sample-bucket-yukinagae]

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

AWS console側でも確認

再度 terraform plan しても差分がが無いことがわかる

$ terraform plan
aws_s3_bucket.sample: Refreshing state... [id=sample-bucket-yukinagae]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

成果物

以下のようなファイル・ディレクトリがあるはず。

$ ls -la
total 24
drwxr-xr-x   6 yuki.nagae  staff   192 Jun 25 23:54 .
drwxr-xr-x  46 yuki.nagae  staff  1472 Jun 25 21:21 ..
drwxr-xr-x   3 yuki.nagae  staff    96 Jun 25 23:40 .terraform
-rw-r--r--   1 yuki.nagae  staff  1407 Jun 25 23:41 .terraform.lock.hcl
-rw-r--r--   1 yuki.nagae  staff   447 Jun 25 23:48 main.tf
-rw-r--r--   1 yuki.nagae  staff  2638 Jun 25 23:53 terraform.tfstate

[main.tf](http://main.tf) の最終的な中身

terraform {
  // terraformのバージョンを指定
  required_version = ">= 1.5.1"

  // awsプロバイダーのバージョンを指定
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }
}

// awsプロバイダーの設定
provider "aws" {
  // regionを指定
  region = "us-east-1"
}

// s3バケットを作成
resource "aws_s3_bucket" "sample" {
  bucket = "sample-bucket-[your name]" // s3バケット名をユニークにするために自分の名前など入れる
  // i.e. bucket = "sample-bucket-yukinagae"
}

参考資料

CureApp テックブログ

Discussion