Reputation: 13571
I'm using aws-sdk to list all the running EC2 instances whose IAM Role is The_Name_of_My_IAM_Role
.
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}`)
}
})
I expect the code to return 6 EC2 instances. But it returns only 4 of them.
The problem doesn't occur if I type 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"
command in my terminal.
I mean aws ec2 describe-instances ...
command returns all 6 EC2 instances.
I've set the following environment variables before running aws ec2 describe-instances ...
command.
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_DEFAULT_PROFILE=my_profile
I also have my_profile
defined in ~/.aws/credentials
file.
What might be wrong my node.js code?
Or is this a bug of aws-sdk
?
Upvotes: 3
Views: 2275
Reputation: 2599
Here is a shell script (using aws-cli) to loop through all regions and display all ec2 instances within a table:
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
there should be the same methods for node.js
Upvotes: 1
Reputation: 269322
Please note that Reservations contain Instances.
When multiple instances are launched via one command (eg launching two identical instances in the console), then both instances are part of a single Reservation.
Your code is counting the number of Reservations, but you are actually expecting the count to include the number of instances in all Reservations.
Solution: Loop through the reservations and add up the number of instances in each Reservation.
Upvotes: 3