created: 2024-01-06T08:50:36.171Z

tfenv を使って terraform init まで

terraform はバージョン違いでなかなか面倒があるので、管理ツールを使う。

tfenv のインストール

brew ではいる。

brew install tfenv

インストールする terraform のバージョン

こちらにインストールが推奨されるバージョンが書いてある。これを書いているときは 1.6.6 になっていた。

環境変数

環境変数で利用する terraform のバージョンを固定できる。

export TFENV_ARCH=amd64
export TFENV_TERRAFORM_VERSION=1.6.6

.bashrc などに書いておくとマシンごとに同じバージョンのファイルを入れられて便利。

ちなみに Apple シリコンを使っている場合でも TFENV_ARCH=amd64 としておかないと、init するときに古いプロバイダが動かなかったりするので、それで TFENV_ARCH を設定している。

terraform のインストール

インストールも簡単にできる。

tfenv install

gnupg が keybase のどちらかがインストールされているとバイナリを検証してくれるようだ。(両方入っていないと以下の警告がでる)

Not instructed to use Local PGP (/opt/homebrew/Cellar/tfenv/3.0.0/use-{gpgv,gnupg}) & No keybase install found, skipping OpenPGP signature verification

terraform init

たぶん最小限だとこんな設定をすると init でプロバイダが色々入ってくれる。

terraform {
  required_version = "1.6.6"

  backend "s3" {
    bucket  = "myterraform-backend"
    key     = "tfstate--domains"
    profile = "myadmin"
    region  = "ap-northeast-1"
  }

  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "..."
    }
    google = {
      source  = "hashicorp/google"
      version = "..."
    }
  }
}

provider "aws" {
  region  = "ap-northeast-1"
  profile = "myadmin"
}
$ terraform init

Initializing the backend...
Initializing modules...

Initializing provider plugins...
- Reusing previous version of hashicorp/template from the dependency lock file
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v4.67.0
- Using previously-installed hashicorp/template v2.2.0

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 して動作確認。

$ terraform plan
現代経済学の直観的方法
[ad] 現代経済学の直観的方法
長沼伸一郎 (Kindle版)