【问题标题】:aws sdk ec2.describeInstances not listing all EC2 instancesaws sdk ec2.describeInstances 未列出所有 EC2 实例
【发布时间】:2018-04-05 20:33:20
【问题描述】:

我正在使用aws-sdk 列出所有正在运行的 IAM 角色为 The_Name_of_My_IAM_Role 的 EC2 实例。

const AWS = require('aws-sdk')

let credentials = new AWS.SharedIniFileCredentials({
  profile: 'my_profile'
})
AWS.config.credentials = credentials
AWS.config.update({
  region: 'ap-northeast-1'
})

const ec2 = new AWS.EC2()

let params = {
  Filters: [
    {
      Name: 'iam-instance-profile.arn',
      Values: [`arn:aws:iam::123456789123:instance-profile/The_Name_of_My_IAM_Role`]
    },
    {
      Name: 'instance-state-name',
      Values: ['running']
    }
  ]
}
ec2.describeInstances(params, (err, data) => {
  if (err) {
    console.log(`describeInstances error: ${err}`)
  } else {
    console.log(`data.Reservations.length: ${data.Reservations.length}`)
  }
})

我希望代码返回 6 个 EC2 实例。但它只返回其中的 4 个。

如果我在终端中输入aws ec2 describe-instances --filters "Name=iam-instance-profile.arn,Values=arn:aws:iam::123456789123:instance-profile/The_Name_of_IAM_Role" "Name=instance-state-name,Values=running" 命令,则不会出现此问题。

我的意思是 aws ec2 describe-instances ... 命令返回所有 6 个 EC2 实例。

在运行aws ec2 describe-instances ... 命令之前,我已经设置了以下环境变量。

export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_DEFAULT_PROFILE=my_profile

我还在~/.aws/credentials 文件中定义了my_profile

我的 node.js 代码可能有什么问题?

或者这是aws-sdk的bug?

【问题讨论】:

  • 返回的 4 个是从 CLI 返回的 6 个的一部分吗? (也就是说,它们是 相同的 个实例吗?)如果您删除过滤器,结果是否(至少)包含您预期的 6 个实例?

标签: node.js amazon-web-services aws-sdk


【解决方案1】:

请注意,预留包含实例。

当通过一个命令启动多个实例时(例如在控制台中启动两个相同的实例),那么这两个实例都是单个 Reservation 的一部分。

您的代码正在计算 Reservations 的数量,但您实际上希望该计数包括所有 Reservations 中的实例数。

解决方案:遍历预留并将每个预留中的实例数相加。

【讨论】:

  • 你是对的。我发现预留中包含 2 个实例。
【解决方案2】:

这是一个 shell 脚本(使用 aws-cli)循环遍历所有区域并在一个表中显示所有 ec2 实例:

for region in $(aws ec2 describe-regions --query 'Regions[*].RegionName' --output text); do
   echo "Region: $region"
   aws ec2 describe-instances --region $region --query "Reservations[*].Instances[*].{name: Tags[?Key=='Name'] | [0].Value, instance_id: InstanceId, ip_address: PrivateIpAddress, state: State.Name}" --output table
done

node.js 应该有相同的方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 2015-04-17
    • 1970-01-01
    相关资源
    最近更新 更多