fix(ec2): reject duplicate key pair names in ImportKeyPair (#1848)

ImportKeyPair accepted any KeyName even when a key pair with the same
name already existed in the region, so DescribeKeyPairs could list
multiple entries with the same name (e.g. after repeated terraform
apply runs). Real AWS rejects this with InvalidKeyPair.Duplicate.

Apply the same duplicate-name check that CreateKeyPair already
performs, scoped to the region.

Fixes #1845
This commit is contained in:
Ankit1324 authored and GitHub committed 2026-07-14 22:27:15 -04:00
1 parent 483cc5b180
commit f9360cbf86
3 files changed
+52

No files matched your search

@@ -1572,6 +1572,11 @@ public class Ec2Service {
public KeyPair importKeyPair(String region, String keyName, String publicKeyMaterial) {
ensureDefaultResources(region);
boolean exists = keyPairs.scan(k -> true).stream()
.anyMatch(k -> k.getRegion().equals(region) && k.getKeyName().equals(keyName));
if (exists) {
throw new AwsException("InvalidKeyPair.Duplicate", "The keypair '" + keyName + "' already exists", 400);
}
String keyPairId = "key-" + randomHex(17);
KeyPair kp = new KeyPair();
kp.setKeyPairId(keyPairId);