8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【HCL】TerraformでECRへPushする

Posted at

なぜやる

Terraform で環境構築時、コンテナイメージがないと、起動失敗しますので、そうなると、ECR作った直後に、コンテナイメージが作成できれば、後続のサービスも順調に作成できます。

どうやる

Terraformprovisioner という機能が持っており、リモート/ローカルで任意のコマンドを実行できます。

やってみる

まず docker build 用のスクリプトを作って、Terraform か呼び出し、プッシュしてもらう感じ、スクリプトが変更されたら、再実行できるトリガーも追加します。

dockerbuild.sh
#!/bin/bash

# Docker login
aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com

# Build image
docker build -t $CONTAINER_NAME .

# Tag
docker tag $CONTAINER_NAME:latest $REPO_URL:latest

# Push image
docker push $REPO_URL:latest
main.tf
# ----------------------------------------------------------
# ECR
# ----------------------------------------------------------
resource "aws_ecr_repository" "frontend" {
  name                 = "frontend"
  image_tag_mutability = "MUTABLE"
  image_scanning_configuration {
    scan_on_push = true
  }
}

# ----------------------------------------------------------
# Null Resource
# ----------------------------------------------------------
resource "null_resource" "frontend" {
  triggers = {
    // MD5 チェックし、トリガーにする
    file_content_md5 = md5(file("${path.module}/dockerbuild.sh"))
  }

  provisioner "local-exec" {
    // ローカルのスクリプトを呼び出す
    command = "sh ${path.module}/dockerbuild.sh"

    // スクリプト専用の環境変数
    environment = {
      AWS_REGION     = local.region
      AWS_ACCOUNT_ID = local.account_id
      REPO_URL       = aws_ecr_repository.frontend.repository_url
      CONTAINER_NAME = "frontend"
    }
  }
}
dockerbuild.sh
#!/bin/bash

# Docker login
aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com

# Build image
docker build -t $CONTAINER_NAME .

# Tag
docker tag $CONTAINER_NAME:latest $REPO_URL:latest

# Push image
docker push $REPO_URL:latest

最後に

provisioner はたくさんのユーズケースに使えますので、詳しい情報は下記サイトまで。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?