🌟

docker-composeでTerraformを実行できるようにしてみた

2023/05/27に公開

はじめに

docker-composeでTerraformを実行するために必要な準備について書いていきたいと思います。
Terraformの実行先については、AWSになります。

前提

  • 既にTerraformのコードが用意されている状態
  • AWSにて作業用のIAMユーザーを作成済みの状態
  • PCはMacOSを使用
バージョン情報
$ sw_vers
ProductName:		macOS
ProductVersion:		13.2.1
BuildVersion:		22D68
  • Docker Desktopのインストールが完了していて、起動済みの状態

https://www.docker.com/products/docker-desktop/

イメージ図

準備

1.docker-compose.yamlの準備

Terraformのコードが格納されているルートディレクトリ直下に docker-compose.yaml を用意する。

docker-compose.yaml
version: "3"

services:
  terraform:
    image: hashicorp/terraform:1.4.6
    volumes:
      - ~/.aws:/root/.aws:ro
      - ./:/workdir
    working_dir: "/workdir"
    environment:
      - AWS_ACCESS_KEY_ID
      - AWS_SECRET_ACCESS_KEY
      - AWS_SESSION_TOKEN
      - AWS_REGION
      - AWS_DEFAULT_REGION
      - AWS_PROFILE

image の部分でTerraformのバージョンを指定する。(今回は1.4.6)

バージョン情報については、以下のリンクを参照下さい。

https://hub.docker.com/r/hashicorp/terraform/tags

2.AWS認証情報の用意

同じくTerraformのコードが格納されているルートディレクトリ直下に .envrc を作成する。

.envrc
export AWS_PROFILE=terraform

アクセスキー、シークレットアクセスキーは以下のように、 ~/.aws/credentials に記載する。

credentials
[terraform]
aws_access_key_id = <アクセスキー>
aws_secret_access_key = <シークレットアクセスキー>

実行確認

Terraformのワークスペースの初期化をするためのコマンドを入力する。

コマンド
docker-compose run --rm terraform init

こちらを実行して、正常にTerraformのコマンドが動作しているようであれば問題なし。

実行例
$ docker-compose run --rm terraform init
Creating test_terraform_terraform_run ... done

Initializing the backend...
Initializing modules...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Installing hashicorp/aws v4.34.0...
- Installed hashicorp/aws v4.34.0 (signed by HashiCorp)

Terraform has made some changes to the provider dependency selections recorded
in the .terraform.lock.hcl file. Review those changes and commit them to your
version control system if they represent changes you intended to make.

〜〜省略〜〜

参考記事

https://zenn.dev/isseeeeey55/articles/48352513fa8123

Discussion