Skip to content

Instantly share code, notes, and snippets.

@raviagheda
Last active September 14, 2025 01:02
Show Gist options
  • Save raviagheda/c69ae5e884f4490b1af656dbd80c00dd to your computer and use it in GitHub Desktop.
Save raviagheda/c69ae5e884f4490b1af656dbd80c00dd to your computer and use it in GitHub Desktop.
Github Action with EC2 using SSH

Github Action with EC2 using SSH

Check this out on Dev.to

Configure SSH into aws ec2

Declare these git secrets

  • SSH_PRIVATE_KEY
  • HOST_NAME / IP_ADDRESS
  • USER_NAME
name: Deploy

on:
  push:
    branches: [ dev ]

jobs:
  Deploy:
    name: Deploy to EC2
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v2 
      - name: Build & Deploy
        env:
            PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
            HOSTNAME: ${{secrets.SSH_HOST}}
            USER_NAME: ${{secrets.USER_NAME}}
      
        run: |
          echo "$PRIVATE_KEY" > private_key && chmod 600 private_key
          ssh -o StrictHostKeyChecking=no -i private_key ${USER_NAME}@${HOSTNAME} '

              # Now we have got the access of EC2 and we will start the deploy .
              cd /home/ubuntu/<PROJECT_DIRECTORY> &&
              git checkout dev &&
              git fetch --all &&
              git reset --hard origin/dev &&
              git pull origin dev &&
              sudo npm i &&
              sudo npm run build &&
              sudo pm2 stop ./dist/index.js &&
              sudo pm2 start ./dist/index.js
              '
@braedonwatkins
Copy link

but how can i allow github actions to connect to ec2 if the ip of the runner needs to be whilelisted?

      - name: Get VPC IP
        id: vpc-ip
        uses: haythem/[email protected]

      - name: Add IP to AWS Security group
        id: get-sg-rule-id
        run: |
          id=$(aws ec2 authorize-security-group-ingress \
            --group-id $SG \
            --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges="[{CidrIp=${IP},Description=${DESC}}]" \
            | jq --raw-output '.SecurityGroupRules | map(.SecurityGroupRuleId) | join("")')
          echo "::set-output name=rule_id::$id"
        env:
          IP: ${{ steps.vpc-ip.outputs.ipv4 }}/32
          DESC: 'Github'

Forgive me if I'm misunderstanding but is the idea to piece by piece add new IPs permanently to the sec groups until we fully map all those to GitHub Runners? IDK how often these change or get released so I'm hesitant to do it this but it seems like the best solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment