

适用于 JavaScript 的 AWS SDK v2 已终止支持。建议您迁移到 [适用于 JavaScript 的 AWS SDK v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/)。有关更多详情和如何迁移的信息，请参阅本[公告](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)。

# 管理 Amazon EC2 实例
<a name="ec2-example-managing-instances"></a>

![JavaScript code example that applies to Node.js execution](http://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**此 Node.js 代码示例演示：**
+ 如何检索有关 Amazon EC2 实例的基本信息。
+ 如何启动和停止对 Amazon EC2 实例的详细监控。
+ 如何启动和停止 Amazon EC2 实例。
+ 如何重启 Amazon EC2 实例。

## 情景
<a name="ec2-example-managing-instances-scenario"></a>

在本示例中，您使用一系列 Node.js 模块执行多个基本实例管理操作。这些 Node.js 模块使用 SDK for JavaScript，通过以下 Amazon EC2 客户端类方法管理实例：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#monitorInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#monitorInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#unmonitorInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#unmonitorInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#startInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#startInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#stopInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#stopInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#rebootInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#rebootInstances-property)

有关 Amazon EC2 实例的生命周期的更多信息，请参阅《Amazon EC2 用户指南》**中的[实例生命周期](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html)。

## 先决条件任务
<a name="ec2-example-managing-instances-prerequisites"></a>

要设置和运行此示例，请先完成以下任务：
+ 安装 Node.js。有关安装 Node.js 的更多信息，请参阅 [Node.js 网站](https://nodejs.org)。
+ 使用用户凭证创建共享配置文件。有关提供共享凭证文件的更多信息，请参阅[从共享凭证文件加载 Node.js 中的凭证](loading-node-credentials-shared.md)。
+ 创建 Amazon EC2 实例。有关创建 Amazon EC2 实例的更多信息，请参阅《Amazon EC2 用户指南》**中的 [Amazon EC2 实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html)，或《Amazon EC2 用户指南》**中的 [Amazon EC2 实例](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/Instances.html)。

## 描述实例
<a name="ec2-example-managing-instances-describing"></a>

创建文件名为 `ec2_describeinstances.js` 的 Node.js 模块。请确保按前面所示配置开发工具包。要访问 Amazon EC2，请创建 `AWS.EC2` 服务对象。调用 Amazon EC2 服务对象的 `describeInstances` 方法来检索实例的详细说明。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  DryRun: false,
};

// Call EC2 to retrieve policy for selected bucket
ec2.describeInstances(params, function (err, data) {
  if (err) {
    console.log("Error", err.stack);
  } else {
    console.log("Success", JSON.stringify(data));
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node ec2_describeinstances.js
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_describeinstances.js)找到。

## 管理实例监控
<a name="ec2-example-managing-instances-monitoring"></a>

创建文件名为 `ec2_monitorinstances.js` 的 Node.js 模块。请确保按前面所示配置开发工具包。要访问 Amazon EC2，请创建 `AWS.EC2` 服务对象。添加您要控制监控的实例的实例 ID。

根据命令行参数的值（`ON` 或 `OFF`），调用 Amazon EC2 服务对象的 `monitorInstances` 方法来启动对指定实例的详细监控，或者调用 `unmonitorInstances` 方法。使用 `DryRun` 参数，在您尝试更改这些实例的监控之前，测试您是否有权限更改实例监控。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  InstanceIds: ["INSTANCE_ID"],
  DryRun: true,
};

if (process.argv[2].toUpperCase() === "ON") {
  // Call EC2 to start monitoring the selected instances
  ec2.monitorInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.monitorInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.InstanceMonitorings);
        }
      });
    } else {
      console.log("You don't have permission to change instance monitoring.");
    }
  });
} else if (process.argv[2].toUpperCase() === "OFF") {
  // Call EC2 to stop monitoring the selected instances
  ec2.unmonitorInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.unmonitorInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.InstanceMonitorings);
        }
      });
    } else {
      console.log("You don't have permission to change instance monitoring.");
    }
  });
}
```

要运行此示例，请在命令行中键入以下内容，指定 `ON` 以启动详细监控，或者指定 `OFF` 以停止监控。

```
node ec2_monitorinstances.js {{ON}}
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_monitorinstances.js)找到。

## 启动和停止实例
<a name="ec2-example-managing-instances-starting-stopping"></a>

创建文件名为 `ec2_startstopinstances.js` 的 Node.js 模块。请确保按前面所示配置开发工具包。要访问 Amazon EC2，请创建 `AWS.EC2` 服务对象。添加您要启动或停止的实例的实例 ID。

根据命令行参数的值（`START` 或 `STOP`），调用 Amazon EC2 服务对象的 `startInstances` 方法来启动指定实例，或者调用 `stopInstances` 方法来停止实例。首先使用 `DryRun` 参数来测试您是否有权限，然后再尝试启动或停止所选实例。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  InstanceIds: [process.argv[3]],
  DryRun: true,
};

if (process.argv[2].toUpperCase() === "START") {
  // Call EC2 to start the selected instances
  ec2.startInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.startInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.StartingInstances);
        }
      });
    } else {
      console.log("You don't have permission to start instances.");
    }
  });
} else if (process.argv[2].toUpperCase() === "STOP") {
  // Call EC2 to stop the selected instances
  ec2.stopInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.stopInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.StoppingInstances);
        }
      });
    } else {
      console.log("You don't have permission to stop instances");
    }
  });
}
```

要运行此示例，请在命令行中键入以下内容，指定 `START` 以启动实例，或者指定 `STOP` 以停止实例。

```
node ec2_startstopinstances.js {{START}} {{INSTANCE_ID}}
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_startstopinstances.js)找到。

## 重启实例
<a name="ec2-example-managing-instances-rebooting"></a>

创建文件名为 `ec2_rebootinstances.js` 的 Node.js 模块。请确保按前面所示配置开发工具包。要访问 Amazon EC2，请创建 Amazon EC2 服务对象。添加您要重启的实例的实例 ID。调用 `AWS.EC2` 服务对象的 `rebootInstances` 方法来重启指定的实例。首先使用 `DryRun` 参数来测试您是否有权限重启这些实例，然后再尝试重启它们。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  InstanceIds: ["INSTANCE_ID"],
  DryRun: true,
};

// Call EC2 to reboot instances
ec2.rebootInstances(params, function (err, data) {
  if (err && err.code === "DryRunOperation") {
    params.DryRun = false;
    ec2.rebootInstances(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else if (data) {
        console.log("Success", data);
      }
    });
  } else {
    console.log("You don't have permission to reboot instances.");
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node ec2_rebootinstances.js
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_rebootinstances.js)找到。