diff --git a/rustv1/examples/ec2/src/ec2.rs b/rustv1/examples/ec2/src/ec2.rs index a9aa0e6c1bb..da8944ec4a7 100644 --- a/rustv1/examples/ec2/src/ec2.rs +++ b/rustv1/examples/ec2/src/ec2.rs @@ -62,12 +62,12 @@ impl EC2Impl { // snippet-end:[ec2.rust.list_keys.impl] // snippet-start:[ec2.rust.delete_key.impl] - pub async fn delete_key_pair(&self, key_pair_id: &str) -> Result<(), EC2Error> { - let key_pair_id: String = key_pair_id.into(); - tracing::info!("Deleting key pair {key_pair_id}"); + pub async fn delete_key_pair(&self, key_name: &str) -> Result<(), EC2Error> { + let key_name: String = key_name.into(); + tracing::info!("Deleting key pair {key_name}"); self.client .delete_key_pair() - .key_pair_id(key_pair_id) + .key_name(key_name) .send() .await?; Ok(()) diff --git a/rustv1/examples/ec2/src/getting_started/key_pair.rs b/rustv1/examples/ec2/src/getting_started/key_pair.rs index 4528e555605..d2bacc0ddc4 100644 --- a/rustv1/examples/ec2/src/getting_started/key_pair.rs +++ b/rustv1/examples/ec2/src/getting_started/key_pair.rs @@ -50,23 +50,27 @@ impl KeyPairManager { let (key_pair, material) = ec2 .create_key_pair(key_name.clone()) .await - .map_err(|e| e.add_message(format!("Couldn't create key {key_name}")))?; + .map_err(|e| { + self.key_pair = KeyPairInfo::builder().key_name(key_name.clone()).build(); + e.add_message(format!("Couldn't create key {key_name}")) + })?; let path = self.key_file_dir.join(format!("{key_name}.pem")); - util.write_secure(&key_name, &path, material)?; - - self.key_file_path = Some(path); + // Save the key_pair information immediately, so it can get cleaned up if write_secure fails. + self.key_file_path = Some(path.clone()); self.key_pair = key_pair.clone(); + util.write_secure(&key_name, &path, material)?; + Ok(key_pair) } // snippet-end:[ec2.rust.create_key.wrapper] // snippet-start:[ec2.rust.delete_key.wrapper] pub async fn delete(self, ec2: &EC2, util: &Util) -> Result<(), EC2Error> { - if let Some(key_pair_id) = self.key_pair.key_pair_id() { - ec2.delete_key_pair(key_pair_id).await?; + if let Some(key_name) = self.key_pair.key_name() { + ec2.delete_key_pair(key_name).await?; if let Some(key_path) = self.key_file_path() { if let Err(err) = util.remove(key_path) { eprintln!("Failed to remove {key_path:?} ({err:?})");