Reputation: 5237
I am trying to use the describeInstances function in amazon ec2 to get details about my instance using my tag id. In the documentation it mentions use the filter,
tag:key=value - The key/value combination of a tag assigned to the resource, where tag:key is the tag's key.
I tried it in the following way:
var params1 = {
Filters : [
{
Tags : [ {
Key : key_name,
Value : key_value
} ]
}
]
};
ec2.describeInstances(params1, function(data, err) {
})
, but I get an error: Unexpected Token at Tags : What is the correct way to use this api?
Upvotes: 3
Views: 5368
Reputation: 114
For those using version 3 of the JS AWS-SDK; there have been some changes since v2. You'd now use DescribeInstancesCommand.
From that page:
import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2"; // ES Modules import
// const { EC2Client, DescribeInstancesCommand } = require("@aws-sdk/client-ec2"); // CommonJS import
const client = new EC2Client(config);
const input = { // DescribeInstancesRequest
Filters: [ // FilterList
{ // Filter
Name: "STRING_VALUE",
//tag: - The key/value combination of a tag assigned to the resource.
//Use the tag key in the filter name and the tag value as the filter value.
//For example, to find all resources that have a tag with the key Owner and the value TeamA, specify tag:Owner for the filter name and TeamA for the filter value.
Values: [ // ValueStringList
"STRING_VALUE",
],
},
],
InstanceIds: [ // InstanceIdStringList
"STRING_VALUE",
],
DryRun: true || false,
MaxResults: Number("int"),
NextToken: "STRING_VALUE",
};
const command = new DescribeInstancesCommand(input);
const response = await client.send(command);
Here config
can, for example, contain the region
(see more at the bottom of https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/).
Upvotes: 0
Reputation: 339
The documentation is a little confusing, but you need to construct a filter name that includes the tag: prefix and your tag name. Here's a working example:
var AWS = require('aws-sdk');
var ec2 = new AWS.EC2({
region: 'eu-west-1'
});
var params = {
Filters: [
{
Name: 'tag:Project',
Values: ['foo']
}
]
};
ec2.describeInstances(params, function (err, data) {
if (err) return console.error(err.message);
console.log(data);
});
This returns all instances that have the tag Project set to the value foo.
Upvotes: 17