aboutsummaryrefslogtreecommitdiff
path: root/control/start-instance
blob: 1b6ce9b3c742703a71a427858920a3f3ae85ad35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/bin/bash
###############################################################################
# Copyright (c) 2011 Linaro
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
###############################################################################
#
# Script/functions to create EC2 instance and make sure it's running
#

function ec2_create_instance() {
    local keypair=$1
    local ami=$2
    local instance_type=$3
    local security_groups="$4"
    local zone=$5
    echo "Creating instance..."
    local cmd="ec2-run-instances $ami -k $keypair -t $instance_type --availability-zone=$zone $security_groups"
#    echo $cmd
    instance_id=`$cmd | grep ^INSTANCE | cut -f2`
    if [ -z "$instance_id" ]; then
        echo "Error executing: $cmd"
        exit 1
    fi
}

function ec2_wait_till_running() {
    local instance=$1
    echo -n "Waiting for instance to start..."
    while true; do
        instance_hostname=`ec2-describe-instances $instance | grep ^INSTANCE | cut -f4`
        if [ -n "$instance_hostname" ]; then
            break
        fi
        sleep 1
        echo -n .
    done
    echo
}

function ec2_wait_till_booted() {
    local hostname=$1
    echo -n "Waiting for instance to boot..."
#    echo ssh -o StrictHostKeyChecking=no ubuntu@$hostname true
    cnt=0
    while true; do
        cnt=$(($cnt + 1))
        ssh -q -o StrictHostKeyChecking=no ubuntu@$hostname true
        rc=$?
#        echo "try$cnt: rc=$rc"
        echo -n .
        if [ $rc -eq 0 ]; then
            break
        fi
        if [ $cnt -gt 20 ]; then
            break
        fi
        sleep 1
    done
    echo
    [ $rc -eq 0 ]
}

function ec2_start_instance() {
    ec2_create_instance "$1" "$2" "$3" "$4" "$5"
    ec2_wait_till_running $instance_id
    if ! ec2_wait_till_booted $instance_hostname; then
        echo "Error starting instance"
    fi
}


if [ "$1" != "--include" ]; then

    if [ "$1" == "" ]; then
        echo "Usage: $0 <ec2 keypair name> <AMI> <instance type> <security groups>"
        exit
    fi

    ec2_start_instance $1
    echo "Instance ID: $instance_id"
    echo "Hostname: $instance_hostname"

fi