ubuntu4aws

Automating the deployment of calculations on a platform such as AWS is an important issue in order to increase the productivity of Computational Fluid Dynamics (CFD) studies. Indeed a company should charge for the time spent developing the model and not not while performing command line sessions, which are difficult to remember when they are not practiced on a daily basis.

EIF-services has therefore successfully tested the procedure described here:

  • initial configuration in the AWS console (web interface);
  • writing a script to (i) start an Ubuntu instance on AWS, (ii) connect to it and (iii) release resources after the job is done. You will find this bash script below.

This is an important milestone on the path to CFD on AWS. In particular, the script was used several weeks after its development, when the options of the aws command had been completely forgotten by the operator.

N.B. The following script is compatible with the 12 months free offer of AWS, provided of course one does not to forget to release the AWS resources (-t).

#!/usr/bin/env bash

usage() {
  cat << HEREDOC
Usage: ubuntu4aws.sh (-h|-r|-l|-t)
-h: Help
-r: Run instance
-l: Log in
-t: Terminate
N.B. Assuming table output (aws configure).
HEREDOC
}

INSTANCE_ID=''
IP_ADDRESS=''
get_id_ip() {
  if [ -e $OUT1 ]; then
    INSTANCE_ID=$(awk '$0~"InstanceId"{print $4}' < $OUT1)
    [ -e $OUT2 ] || aws ec2 describe-instances --instance-ids $INSTANCE_ID > $OUT2
    IP_ADDRESS=$(awk '$0~"PublicIpAddress"{print $4}' < $OUT2)
  else
    echo "Instance not started yet!"; exit 0
  fi
}

AMI_ID=ami-045a8ab02aadf4f88
INSTANCE_TYPE=t2.micro
SECURITY_GROUP=launch-wizard-1
SSH_PAIR=EC2#2
PRIVATE_KEY=~/EIF/AWS/credentials/EC2#2.pem
OUT1=~/tmp/out1.txt
OUT2=~/tmp/out2.txt

while getopts 'hrlt' option; do
  case $option in
    h) usage; exit 0;;
    r) if [ -e $OUT1 ]; then
         echo "Instance already running."; exit 0
       else
         aws ec2 run-instances --image-id $AMI_ID --instance-type $INSTANCE_TYPE \
         --security-groups $SECURITY_GROUP --key-name $SSH_PAIR > $OUT1
       fi
    ;;
    l) get_id_ip
       ssh -i $PRIVATE_KEY ubuntu@$IP_ADDRESS
    ;;
    t) get_id_ip
       aws ec2 terminate-instances --instance $INSTANCE_ID
       rm $OUT1 $OUT2 ~/.ssh/known_hosts
    ;;
    ?) usage; exit 1;;
  esac
done