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

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com