image.png

BeforeInstall.sh

#!/bin/bash
if [ -d /opt/scripts/ ]; then
    sudo rm -rf /opt/scripts/
fi

mkdir -p /opt/scripts/

AfterInstall.sh

#!/bin/bash
sudo yum install docker -y
sudo systemctl enable docker
sudo usermod -aG docker ec2-user
sudo usermod -aG docker root
sudo systemctl start docker
sudo chmod 666 /var/run/docker.sock

docker --version

ApplicationStart.sh

#!/bin/bash
aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin 362708816803.dkr.ecr.ap-northeast-2.amazonaws.com
docker pull 362708816803.dkr.ecr.ap-northeast-2.amazonaws.com/wsi-app:latest
docker tag 362708816803.dkr.ecr.ap-northeast-2.amazonaws.com/wsi-app:latest wsi-app:latest
docker run -d -p 8080:8080 wsi-app:latest
aws ecr batch-delete-image --repository-name wsi-app --image-ids imageTag=latest

ApplicationStop.sh

#!/bin/bash
docker rm -f $(docker ps -a -q)
docker rmi -f $(docker images -q)

appspec.yml

version: 0.0
os: linux
files:
  - source: /
    destination: /opt/scripts/
hooks:
  AfterInstall:
    - location: scripts/AfterInstall.sh
      timeout: 60
      runas: root
  ApplicationStart:
    - location: scripts/ApplicationStart.sh
      timeout: 60
      runas: root
  ApplicationStop:
    - location: scripts/ApplicationStop.sh
      timeout: 60
      runas: root

buildspec.yml

version: 0.2

env:
  variables:
    AWS_REGION: "REGION"
    ECR_REPO_NAME: "ECR_REPO_NAME"
    AWS_ACCOUNT_ID: "AWS_ACCOUNT_ID"

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t $ECR_REPO_NAME .
      - docker tag $ECR_REPO_NAME:latest $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$ECR_REPO_NAME:latest
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker image...
      - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$ECR_REPO_NAME:latest
artifacts:
  files:
    - appspec.yml
    - scripts/AfterInstall.sh
    - scripts/ApplicationStart.sh
    - scripts/ApplicationStop.sh