Search code examples
amazon-web-servicesamazon-ec2aws-sdkaws-api-gatewayaws-sdk-nodejs

Start/stop particular EC2 instance from other EC2 instance in same AWS account


What is a simple way to start/stop a particular (e.g. with hardcoded identifier) EC2 instance from another EC2 instance (running Node) in the same AWS account?

I am familiar with Node but not with AWS SDK, which I suppose I have to learn. At the same time I wonder whether there may be another AWS service in which I can more easily associate an HTTP resource (e.g. modifiable by credentialed PUT/DELETE) with the state (running/stopped) of particular EC2 instance.


Solution

  • You can do it with either the aws cli or the SDK.

    AWS CLI

    A very simple way is just to install the aws cli on the second instance and run

    aws ec2 start-instances --instance-ids i-1234567890abcdef0
    

    or

    aws ec2 stop-instances --instance-ids i-1234567890abcdef0
    

    SDK

    If you want to stick with node, then you can start/stop an instance this way using the SDK:

     var params = {
      InstanceIds: [
         "i-1234567890abcdef0"
      ]
     };
    
     /* Start */
     ec2.startInstances(params, function(err, data) {
       if (err) console.log(err, err.stack); // an error occurred
       else     console.log(data);           // successful response
     });
    
     /* Stop */
     ec2.stopInstances(params, function(err, data) {
       if (err) console.log(err, err.stack); // an error occurred
       else     console.log(data);           // successful response
     });
    

    Important note

    Note that the instance's IAM role needs to include the following policy (or equivalent)

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "ec2:StartInstances",
            "ec2:StopInstances"
          ],
          "Resource": "*"
        }
      ]
    }
    

    Hope it helps!