How to Change EC2 Instance Type from Terminal/ Script

This tutorial explains, how to modify an EC2 instance type from terminal. Also we will provide command to check an EC2 instance description.

Ec2 Instance

Don't Miss

An Ec2 Instance is a virtual server that provided by Amazon. Virtual Server is in the Amazon Elastic Compute Cloud(EC2) for running application on the Amazon Web Service(AWS).

Install Aws Cli

We already explained, how to install Aws Cli in the previous post. Click here to see previous post

Check Instance Status

We can check status of Instance by running below command:

// Get instance id from console of amazon, instance id something like this -i-08d78a96fbXXXXXXXX
$ aws ec2 describe-instance-status --instance-id i-XXXXXXXXXXXXXXXX

Output:

{
  "InstanceStatuses": [
    {
      "AvailabilityZone": "us-east-1d",
      "InstanceId": "i-XXXXXXXXXXXXXXXX",
      "InstanceState": {
        "Code": 16,
        "Name": "running"
      },
      "InstanceStatus": {
        "Details": [
          {
            "Name": "reachability",
            "Status": "passed"
          }
        ],
        "Status": "ok"
      },
      "SystemStatus": {
        "Details": [
          {
            "Name": "reachability",
            "Status": "passed"
          }
        ],
        "Status": "ok"
      }
    }
  ]
}

Stop Instance

To modify instance type, we need to stop instance first. Run the following the command on terminal to stop instance and get stopping status. We can run this command multiples times to get status. When instance completely stopped then it will return status stopped otherwise stopping.

$ aws ec2 stop-instances --instance-ids i-XXXXXXXXXXXXXXXX

Output:

Modify Instance

After stopped instance, we can change instance type. To change instance type, it is important that instance should be stopped. Run the below command to modify instance.

$ aws ec2 modify-instance-attribute --instance-id i-XXXXXXXXXXXXXXXX --instance-type t3.small

Start Instance

Now start instance after change of instance by running below command:

$ aws ec2 start-instances --instance-ids i-XXXXXXXXXXXXXXXX

Output:

//In process to start instance
{
   "StartingInstances": [
   {
    "CurrentState": {
    "Code": 0,
    "Name": "pending"
   },
   "InstanceId": "i-0714c25c3982a0143",
   "PreviousState": {
     "Code": 80,
     "Name": "stopped"
    }
   }
  ]
}

//After Successfully started
{
  "StartingInstances": [
  {
    "CurrentState": {
    "Code": 16,
    "Name": "running"
  },
  "InstanceId": "i-0714c25c3982a0143",
  "PreviousState": {
    "Code": 16,
    "Name": "running"
   }
  }
 ]
}

Creating a Script in PHP

We are creating a script to modify instance type using php. Using shell_exec() function to shell commands and handling response in PHP. Here first stopped the instance then modify the instance type and again starting instance.

We can make script in any language by using this concept.

<?php

$instance_id = 'i-XXXXXXXXXXXXXX';
$instance_type = 't3.medium';

/**
 * @desc This function is used to change instance type.
 * @return type
 */
function modify_instance_type() {
    $output = shell_exec('aws ec2 modify-instance-attribute --instance-id ' . $GLOBALS['instance_id'] . " --instance-type " . $GLOBALS['instance_type']);
    $response = json_decode($output, true);
    echo PHP_EOL;
    return $response;
}

/**
 * @desc This is Recursion method to stop instance. It will return stopping when it is in progress to stop instance
 * @param type $i
 * @return boolean
 */
function stop_instance($i = 1) {
    echo $i;
    $output = shell_exec('aws ec2 stop-instances --instance-ids ' . $GLOBALS['instance_id']);
    $stop_response = json_decode($output, true);
    echo $stop_response['StoppingInstances'][0]['CurrentState']['Name'];
    if(!empty($stop_response['StoppingInstances']) &amp;
    &amp;
// Name can be pending, stopping, stopped
    $stop_response['StoppingInstances'][0]['CurrentState']['Name'] == "stopped" ) {
        return true;
    } else {
        $i++;
        sleep(200);
        stop_instance($i);
    }
}

/**
 * @desc This is recursive method to start instance
 * @return boolean
 */
function start_instance() {
    $output = shell_exec('aws ec2 start-instances --instance-ids ' . $GLOBALS['instance_id']);
    $stop_response = json_decode($output, true);
    if(!empty($stop_response['StartingInstances'])
// Name can be pending, running,
    &amp;
    &amp;
    ($stop_response['StartingInstances'][0]['CurrentState']['Name'] == "pending")
    || ($stop_response['StartingInstances'][0]['CurrentState']['Name'] == "running")) {
        return true;
    } else {
        sleep(200);
        start_instance();
    }
}

/**
 * @desc this function is used to get status of instance
 * @return boolean
 */
function get_instance_status() {

    $output = shell_exec('aws ec2 describe-instance-status --instance-id ' . $GLOBALS['instance_id']);
    return $response = json_decode($output, true);
    if(($response['InstanceStatuses'][0]['InstanceState']['Name'] == "running" )
    &amp;
    &amp;
    ($response['InstanceStatuses'][0]['InstanceStatus']['Status'] == 'ok')) {
        return true;
    } else {
        return false;
    }
}

//Calling instance stop method
$res = stop_instance();
if ($res) {
//Calling invoice modification method
    modify_instance_type();
//Start instance after instance modification
    start_instance();
}
?>

Runnig Script

Run the below command to execute script, it will automatically change instance type:

$ php ourscript.php

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

How to Install & Setup the Java Development Kit (JDK)

If you do not have the newest JDK already put in in your pc, comply with the steps under. You have to have the JDK put in to run applications. To see which version of...

How to Setup Kotlin Plugin in Android Studio Tutorial

Kotlin is a programming language launched by JetBrains, the official designer of essentially the most intelligent Java IDE, named Intellij IDEA. One nice information of shifting to Kotlin is, you...

How to Parse Json in Android Application

JSON stands for JavaScript Object Notation.It is an independent data trade format and is the perfect various for XML. This chapter explains the way to parse the JSON file and...

Related Articles

How to Install & Setup the Java Development Kit (JDK)

If you do not have the newest JDK already put in in your pc, comply with the steps under. You have to have the JDK put in to run applications. To see which version of...

How to Setup Kotlin Plugin in Android Studio Tutorial

Kotlin is a programming language launched by JetBrains, the official designer of essentially the most intelligent Java IDE, named Intellij IDEA. One nice information of shifting to Kotlin is, you...

How to Parse Json in Android Application

JSON stands for JavaScript Object Notation.It is an independent data trade format and is the perfect various for XML. This chapter explains the way to parse the JSON file and...