Alpha Coder

How to Git push to an AWS EC2 remote using a PEM file

AWS provides you with a .pem file when creating an EC2 instance. You can use this file to generate SSH keys for accessing your server without the need for the PEM, as well as push to a remote Git repository on the server. Here’s how…

1. Copy private key in PEM to .ssh folder

1
$ cp /path/to/my-aws-ec2-instance.pem ~/.ssh/id_rsa_ec2

2. Generate and save public key

1
$ ssh-keygen -y -f /path/to/my-aws-ec2-instance.pem > ~/.ssh/id_rsa_ec2.pub

3. Add private key to ssh-agent

Start ssh-agent

1
$ eval "$(ssh-agent -s)"

Then add your key to the agent

1
$ ssh-add ~/.ssh/id_rsa_ec2

At this point, you should be able to access your instance without the PEM file. Instead of:

1
$ ssh -i my-aws-ec2-instance.pem ec2-user@ec2-ip.compute-x.amazonaws.com

Use:

1
$ ssh ec2-user@ec2-ip.compute-x.amazonaws.com

4. Add remote and push

Change directory to your local Git repository and add the remote URL of your server

1
$ git remote add ec2server ec2-user@ec2-ip.compute-1.amazonaws.com:/home/ec2-user/repo.git

Now push…

1
$ git push ec2server
Subscribe to my newsletter for updates on new articles, courses and more. Enjoy the content on Alpha Coder? Please buy me a coffee.

comments powered by Disqus