Search code examples
gitlab-ci

GitLab CI/CD deploy AWS EC2


I'm not sure that my ci/cd configuration file is correct Actually I was trying a lot of ways, but it still return log aws: not found at the gitlab pipline

this is my .gitlab-ci.yml file

image: amazon/aws-cli:latest

stages:
  - build
  - deploy

variables:
  AWS_DEFAULT_REGION: "ap-northeast-2"
  AWS_ECR_REGION: "us-east-1"
  ECR_REGISTRY: "public.ecr.aws/{here_id}"
  AWS_ACCESS_KEY_ID: "access_key"
  AWS_SECRET_ACCESS_KEY: "secret_key"

before_script:
  - aws ecr-public get-login-password --region $AWS_ECR_REGION | docker login --username AWS --password-stdin $ECR_REGISTRY

build:
  stage: build
  image: docker:latest
  script:
    - docker build -t frontend_repo .
    - docker tag frontend_repo:latest $ECR_REGISTRY/frontend_repo:latest
    - docker push $ECR_REGISTRY/frontend_repo:latest
  only:
    - main

deploy:
  stage: deploy
  image: docker:latest
  script:
    - docker stop frontend_container
    - docker rm frontend_container
    - docker rmi $ECR_REGISTRY/frontend_repo:latest
    - docker pull $ECR_REGISTRY/frontend_repo:latest
    - docker run -t -d -p 80:3000 --restart unless-stopped --name frontend_container $ECR_REGISTRY/frontend_repo:latest
    - docker logs -f frontend_container

The main target is connectiong to the AWS -> build & push docker image to AWS ECR -> pull & run docker container on the EC2 instance

for the first look, script seems correct, but I can't connect to the AWS, even with using amazon/aws-cli image as execution environment

Does anyone could check possible issues? The required variables has been added to GitLab CI/CD variables


Solution

  • This issue has been solved by export AWS_ACCESS_KEY_ID=$VARIABLE_NAME_SAVED_IN_GITLABCI_SETTINGS export AWS_SECRET_ACCESS_KEY=$VARIABLE_NAME_SAVED_IN_GITLABCI_SETTINGS on build stage before aws get login

    Also I have used amazon/aws-cli image on build stage and then I'll installing docker

    Also it was been needs a service as docker:dind for using it inside aws image on build stage