Objective

The purpose of this simple exercise is to demonstrate how to remotely execute a command on an EC2 instance using ssh. The general syntax for SSH remote command execution on an EC2 instance is:

ssh –i mykeyfile.pem ec2-user@ip_address 'enter command here'

You’ll need the following additional option for the first SSH connection to a new instance:

-o StrictHostKeyChecking=no
(this is required to suppress the new host key confirmation (yes/no) prompt)

You might also need to use ssh’s –t option where the command uses sudo. Putting the above together, your first ssh command will look something like this:

 $ ssh -t -o StrictHostKeyChecking=no -i mykeyfile.pem ec2-user@52.42.23.2 'pwd'
(replace 'pwd' with a more useful command).

Before executing a remote command from within a Python script, it’s a good idea to print the command string to the console (to help with debugging). You should also print the status and output values for the same reason. You may have noticed that the “yum” package manager on Amazon Linux prompts the user for (yes/no) confirmation before installing a package. This can be suppressed using the yum –y option. For example, to remotely install the Apache webserver on an EC2 instance you might have the following:

ssh -t -o StrictHostKeyChecking=no –i mykeyfile.pem ec2-user@52.42.23.2 'sudo yum -y install httpd'

Exercise

In the Week 2 exercises you put the following bash commands into a Userdata block that is run each time a particular instance is launched.

#!/bin/bash
yum update -y
yum install httpd -y
systemctl enable httpd
systemctl start httpd

You are now required to use the ssh remote command execution syntax to execute the above commands. Two potential errors you may encounter (as mentioned previously) are :

  1. StrictHostKeyChecking
  2. The requirement to use sudo

To summarise, all you need to do is: Create an EC2 instance and get the IP address of the instance. Then at your own Linux command line execute commands similar to ones below (of course you need to include the other required ssh command parameters)

ssh -i keyname ec2-user@ipaddress 'sudo yum update -y'
ssh -i keyname ec2-user@ipaddress 'sudo yum install httpd -y'
etc