Skip to content

Manage the EC2 key pair as a Terraform resource#1

Open
mmshad wants to merge 1 commit into
mainfrom
fix-orphaned-keypair
Open

Manage the EC2 key pair as a Terraform resource#1
mmshad wants to merge 1 commit into
mainfrom
fix-orphaned-keypair

Conversation

@mmshad

@mmshad mmshad commented Jun 27, 2026

Copy link
Copy Markdown
Collaborator

Closes #2

Problem

The key pair is created with boto3 in provision.py and Terraform only
references it by name, so it is never in Terraform state. A plain
terraform destroy does not remove it, and the destroy flow deletes it
only as a separate best effort boto3 call that can be skipped or fail.
The result is orphaned key pairs in AWS.

Fix

provision.py now generates the key locally with ssh-keygen, writes the
private .pem to the workspace at mode 0400, and passes the public key to
a new aws_key_pair resource. Terraform now owns the key pair lifecycle,
so terraform destroy removes it with everything else. The boto3 delete
stays as an idempotent fallback so key pairs from older workspaces are
still cleaned up. The README IAM permission changes from CreateKeyPair
to ImportKeyPair, which is what aws_key_pair uses.

Testing

Verified end to end on a real instance: provisioned a g4dn.xlarge,
confirmed aws_key_pair is in Terraform state, logged in over SSH with
the generated key, then terraform destroy removed the instance and the
key pair. terraform validate and plan also pass.

The key pair is created with boto3 in provision.py and Terraform only
references it by name, so it is never in Terraform state. A plain
terraform destroy does not remove it, and the destroy flow deletes it
only as a separate best effort boto3 call that can be skipped or fail,
leaving orphaned key pairs in AWS.

provision.py now generates the key locally with ssh-keygen and passes
the public key to a new aws_key_pair resource, so Terraform owns its
lifecycle. The boto3 delete stays as an idempotent fallback for
workspaces created before this change. The README IAM permission
changes from CreateKeyPair to ImportKeyPair.
@mmshad mmshad self-assigned this Jun 27, 2026
@mmshad mmshad requested a review from Naeemkh June 27, 2026 04:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Key pairs are not removed on terraform destroy

1 participant