0
0

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 1 year has passed since last update.

RakeでECRにdocker imageをpushする

Posted at

概要

docker imageのbuildからAWS Lambdaへのデプロイまでをrakeで実行できるようにしてみました

作成した動機

  • lambdaでの動作テストのためにdocker imageのpushとlambdaのデプロイが頻繁に発生しており、いくつかのコマンドを何度も実行する必要があった
  • 作成しているアプリケーションはrubyで作成されているため、shell scriptやmakeではなくrubyで完結させたい
  • CIでもrakeを用いることでCI側の記述がシンプルになりそうだった

実装

task default: :docker_build

REGISTORY_URI = 'XXXXXXXXXXXXXXXXXX.dkr.ecr.ap-northeast-1.amazonaws.com'
REPO_NAME = 'ECR REPOSITORY NAME'
IMG_NAME = 'IMG NAME'
TAG_NAME = 'TAG NAME'
FUNCTION_NAME = 'LAMBDA FUNCTION NAME'

task :docker_build do
  sh %(docker build -t #{IMG_NAME} -f ./Dockerfile .)
end

task :aws_login do
  sh %(aws ecr get-login-password | docker login --username AWS --password-stdin #{REGISTORY_URI})
end

task docker_push: %i[docker_build aws_login] do
  sh %(docker tag #{IMG_NAME}:latest #{REGISTORY_URI}/#{REPO_NAME}:#{TAG_NAME})
  sh %(aws ecr batch-delete-image --repository-name #{REPO_NAME} --image-ids imageTag=#{TAG_NAME})
  sh %(docker push #{REGISTORY_URI}/#{REPO_NAME}:#{TAG_NAME})
end

task deploy: :docker_push do
  option = "--function-name=#{FUNCTION_NAME} --image-uri=#{REGISTORY_URI}/#{REPO_NAME}:latest"
  sh %(aws lambda update-function-code --no-publish #{option})
  unless ENV['CI']
    sh %(aws lambda wait function-updated --function-name=#{FUNCTION_NAME})
    puts 'deploy DONE.'
  end
end

task docker_run: :docker_build do
  option = '--rm -it --env-file=./.env --mount type=bind,source=$(pwd),target=/app -p 9000:8080'
  sh %(docker run #{option} #{IMG_NAME})
end

task docker_run_bash: :docker_build do
  option = '--rm -it --env-file=./.env --mount type=bind,source=$(pwd),target=/app --entrypoint "bash"'
  sh %(docker run #{option} #{IMG_NAME})
end

利用方法

# docker imageをbuildしたい
$ rake
# もしくは
$ rake docker_build

# deployしたい
rake deploy

# docker imageからインスタンスを作成してbashで操作したい
rake docker_run_bash
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?