Reputation: 39
I have a long list of aws EC2 instances and I would like to find the keypair associated with a specific instance. However, when I look at the AWS sdk documentation, I see there is a call describeKeyPairs
used as so:
var params = {
KeyNames: [
"my-key-pair"
]
};
ec2.describeKeyPairs(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
/*
data = {
KeyPairs: [
{
KeyFingerprint: "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f",
KeyName: "my-key-pair"
}
]
}
*/
});
which returns a list of keypairs. I can filter this returned list using key-id
key-name
or tags
but I dont see a way to filter it by EC2 instance.
Is this possible to do?
reference: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeKeyPairs-property
Upvotes: 0
Views: 723
Reputation: 39
I was able to discover an answer to this!
ec2.describeInstances
returns a property keyName
which can then be used as a filter in ec2.describeKeyPairs
Upvotes: 1
Reputation: 4077
If you want to get all the instances that uses a specific key pair, you can use the describe-instances operation and add the filter:key-name
var params = {
Filters: [
{
Name: 'key-name',
Values: ['my-key-pair']
}
]
};
ec2.describeInstances(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Otherwise, if you want to get the key pair that is using a particular instance, you can specify the instance id and then read the key-name attribute from response:
var params = {
InstanceIds: [
"i-1234567890abcdef0"
]
};
ec2.describeInstances(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Upvotes: 2