While creating an Amazon EC2 instance a key pair will be generated and you will be asked to download a *.pem file.

This is the key file you will need to login to the instance.

Note: Amazon allows to download *.pem file only once (may be for security reasons) while creating the instance. If you lost it, it is likely that you be able to access the instance again.

SSH connect to EC2 instance

 ssh -i /path/to/pem/file/mypemfile.pem ubuntu@ec2-172-31-121-212.compute-1.amazonaws.com

Ubuntu instances of EC2 has “ubuntu” as defult user name.

ec2-172-31-121-212.compute-1.amazonws.com is the public DNS attached to your instance.

If you have an elastic IP or public IP associated with the instance it is easier to use them.

 ssh -i /path/to/pem/file/mypemfile.pem ubuntu@54.121.12.412

It is likely for the first time you will hit upon unprotected file error with follwing message

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE!                @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0664 for 'mypemfile.pem' are too open.

You need to restrict the file read and execute permission to owner only. Run the following command to set proper permissions on mypemfile.pem

 chmod 400 /path/to/pem/file/mypemfile.pem

If might also need sudo permission to execute above command. Then prepend “sudo ” in the above command.

Now you are good to go and connect.

RSYNC with EC2 instance

Sometimes we develop our websites in local machine and want to publish it in the web. A hassle free way to sync all your website files from local to EC2 instance is “rsync”

Rsync Commands

The command will look like following

sudo rsync -avP -e "sudo ssh -i /path/to/pem/file/mypemfile.pem" /var/www/blog ubuntu@54.121.12.412:/var/www/

If you want to take a back up of the server website then try the following

sudo rsync -avP -e "sudo ssh -i /path/to/pem/file/mypemfile.pem" ubuntu@54.121.12.412:/var/www/blog ~/

Note: I am assuming /var/www/blog is the DocumentRoot of the website

Lets drill a little about the -avP options with rsync

-a options means combination of -rlptgoD where
-r recursive copy of directories
-l copy sym links as sym links
-p preserve permissions
-t preserve modification times
-g preserve group
-o preserve owner
-D preserve special files, devices files

-v verbose

-P keeps partially transferred files and resumes from where it stopped
Also, shows progress of transfer

If you want to remove extraneous files from destination
use –delete options in above commands.