Search code examples
amazon-ec2github-actions

Confused with github action and ec2


This is my github actions flow:

---
name: build and push image to aws ecr
on:
  push: 
    branches: [ main ]
jobs:
  build-and-push:
    name: Build and push to ecr
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v2
    ...

  deploy:
    needs: build-and-push
    name: deploy
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Login ec2
        env:
          PRIVATE_KEY: ${{ secrets.EC2_SSH_KEY }}
          HOSTNAME: ${{ secrets.HOST_DNS }}
          USER_NAME: ${{ secrets.USERNAME }}
        run: |
          echo "$PRIVATE_KEY" > private_key && chmod 600 private_key
          ssh -o StrictHostKeyChecking=no -i private_key ${USER_NAME}@${HOSTNAME}
          ls
          touch helloworld.txt

I wonder that I'm connected to the EC2 instance or not. This is my result after actions, it's list all file of my project. I think I didn't ssh to EC2 successfull becuase I just create EC2 instance and it's empty.

Run echo "$PRIVATE_KEY" > private_key && chmod 600 private_key
Pseudo-terminal will not be allocated because stdin is not a terminal.
Warning: Permanently added '***,18.181.220.91' (ECDSA) to the list of known hosts.
Dockerfile
README.md
docker-compose.yml
nest-cli.json
package-lock.json
package.json
private_key
src
test
tsconfig.build.json
tsconfig.json

This is reference

This is my command to ssh ec2 from client: ssh -i "home-key.pem" [email protected]

If i didn't connnect to EC2 instance, how I do it with github ?

Thanks for your attention.


Solution

  • I wonder that I'm connected to the EC2 instance or not.

    In your SSH commands, add a hostname -a one: it will display the name of the machine you are on.

    That being said, you could use actions/ssh-execute-commands to execute those same commands:

    - name: Execute SSH commmands on remote server
      uses: JimCronqvist/action-ssh@master
      env:
        PRIVATE_KEY: ${{ secrets.EC2_SSH_KEY }}
        HOSTNAME: ${{ secrets.HOST_DNS }}
        USER_NAME: ${{ secrets.USERNAME }}
      with:
        hosts: '${USER_NAME}@${HOSTNAME}'
        privateKey: ${{ secrets.PRIVATE_KEY }}
        debug: false
        command: |
          ls -lah
          hostname -a
          whoami
          touch helloworld.txt