Getting SSH authentication error while connecting to EC2

251 Views Asked by At

As a newbie, I'm trying to upload and run a Dockerfile on EC2 through GitHub Actions but I am getting this error:

ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain.

I configured EC2_PRIVARE_KEY secret with the private key (.pem) which I downloaded while creating an instance.

The same problem still occurs when I use a different private key. Does anyone have a solution to this problem? Thanks in advance!

My GitHub Actions workflow:

name: Deploy to ECR

on:
  push:
    branches: [ master ]

jobs:
  build:
    name: Build Image
    runs-on: ubuntu-latest
    steps:
      - name: Check out code
        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: ap-south-1

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v1

      - name: Build, tag, and push image to Amazon ECR
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          ECR_REPOSITORY: cicd
          IMAGE_TAG: latest
        run: |
          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG 

      - name: Deploy to EC2
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ${{ secrets.EC2_USERNAME }}
          key: ${{ secrets.EC2_PRIVATE_KEY }}
          script: |
            # Connect to the EC2 instance and pull the Docker image
            ssh-keyscan ${{ secrets.EC2_HOST }} >> ~/.ssh/known_hosts
            ssh -o "StrictHostKeyChecking=no" ${{ secrets.EC2_USERNAME }}@${{ secrets.EC2_HOST }} "docker pull my-image:latest"

            # Stop and remove any existing containers running the same image
            ssh -o "StrictHostKeyChecking=no" ${{ secrets.EC2_USERNAME }}@${{ secrets.EC2_HOST }} "docker stop my-container || true"
            ssh -o "StrictHostKeyChecking=no" ${{ secrets.EC2_USERNAME }}@${{ secrets.EC2_HOST }} "docker rm my-container || true"

            # Start a new container with the updated image
            ssh -o "StrictHostKeyChecking=no" ${{ secrets.EC2_USERNAME }}@${{ secrets.EC2_HOST }} "docker run -d --name my-container -p 8383:8383 my-image:latest"
0

There are 0 best solutions below