Deploying docker image to AWS Fargate in GitHub
Let’s deploy a docker image to AWS ECR and further to AWS Fargate. If you don’t have docker installed, now is the time to do it. GitHub Action YML: Create a workflow named main-aws.yml, for example as: name: Deploy to Amazon ECS on: workflow_dispatch: env: AWS_REGION: eu-central-1 # set this to your preferred AWS region, e.g. us-west-1 ECS_SERVICE: test-svc # set this to your Amazon ECS service name ECS_CLUSTER: test-fargate-dev # set this to your Amazon ECS cluster name ECS_TASK_DEFINITION: .aws/td.json CONTAINER_NAME: test # set this to the name of the container in the ECS_TASK_NAME: test-task defaults: run: shell: bash jobs: Build: name: Build runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ env.AWS_REGION }} - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@v1 - name: Get commit hash id: get-commit-hash run: echo "::set-output name=commit-hash::$(git rev-parse --short HEAD)" - name: Get timestamp id: get-timestamp run: echo "::set-output name=timestamp::$(date +'%Y%m%d-%H%M')" - name: Build, tag, and push the image to Amazon ECR id: build-image env: ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} ECR_REPOSITORY: ${{ secrets.AWS_REPO_NAME }} IMAGE_TAG: ${{ steps.get-commit-hash.outputs.commit-hash }}-${{ steps.get-timestamp.outputs.timestamp }} run: | docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG . docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT - name: Create task definition in Amazon ECS run: aws ecs register-task-definition --cli-input-json file://${{ env.ECS_TASK_DEFINITION }} - name: Create svc in Amazon ECS run: aws ecs create-service --cluster ${{ env.ECS_CLUSTER }} --service-name ${{ env.ECS_SERVICE }} --task-definition ${{ env.ECS_TASK_NAME }} --desired-count 1 --capacity-provider-strategy '[{"capacityProvider":"FARGATE_SPOT","weight":100}]' --network-configuration "awsvpcConfiguration={subnets=[subnet-1,subnet-2,subnet-3],securityGroups=[sg-1,sg-2],assignPublicIp=ENABLED}" --region ${{ env.AWS_REGION }} - name: Fill in the new image ID in the Amazon ECS task definition id: task-def uses: aws-actions/amazon-ecs-render-task-definition@v1 with: task-definition: ${{ env.ECS_TASK_DEFINITION }} # same as container name in taks def container-name: ${{ env.CONTAINER_NAME }} image: ${{ steps.build-image.outputs.image }} - name: Deploy Amazon ECS task definition uses: aws-actions/amazon-ecs-deploy-task-definition@v2 with: task-definition: ${{ steps.task-def.outputs.task-definition }} service: ${{ env.ECS_SERVICE }} cluster: ${{ env.ECS_CLUSTER }} wait-for-service-stability: true Details for every step are bellow. ...