fix(ec2): DescribeKeyPairs returns InvalidKeyPair.NotFound for missing names/ids (#1932)

DescribeKeyPairs returned an empty list (HTTP 200 / CLI exit 0) when a
requested KeyName or KeyPairId did not exist, instead of the documented
InvalidKeyPair.NotFound fault. Idempotent callers that treat exit 0 as
"present" then skip creating the key pair.

Fail with InvalidKeyPair.NotFound (400) when any explicitly requested
name or id does not resolve, while an unfiltered describe on an empty
account still returns an empty list.

Fixes #1911
This commit is contained in:
Ankit1324 authored and GitHub committed 2026-07-29 21:55:06 -05:00
1 parent a4356f25fb
commit 7d961068e1
3 files changed
+78 -1

No files matched your search

@@ -1583,8 +1583,27 @@ public class Ec2Service implements ContainerTeardown {
public List<KeyPair> describeKeyPairs(String region, List<String> keyNames, List<String> keyPairIds) {
ensureDefaultResources(region);
return keyPairs.scan(k -> true).stream()
List<KeyPair> regionKeyPairs = keyPairs.scan(k -> true).stream()
.filter(k -> k.getRegion().equals(region))
.collect(Collectors.toList());
// A named/id lookup for a key pair that does not exist is an error in real
// AWS (InvalidKeyPair.NotFound), not an empty result — otherwise idempotent
// callers that treat exit 0 as "present" skip creating the key.
for (String keyName : keyNames) {
if (regionKeyPairs.stream().noneMatch(k -> keyName.equals(k.getKeyName()))) {
throw new AwsException("InvalidKeyPair.NotFound",
"The key pair '" + keyName + "' does not exist", 400);
}
}
for (String keyPairId : keyPairIds) {
if (regionKeyPairs.stream().noneMatch(k -> keyPairId.equals(k.getKeyPairId()))) {
throw new AwsException("InvalidKeyPair.NotFound",
"The key pair ID '" + keyPairId + "' does not exist", 400);
}
}
return regionKeyPairs.stream()
.filter(k -> keyNames.isEmpty() || keyNames.contains(k.getKeyName()))
.filter(k -> keyPairIds.isEmpty() || keyPairIds.contains(k.getKeyPairId()))
.collect(Collectors.toList());