Skip to content

Commit

Permalink
Use key_name when cleaning up duplicate key.
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidSouther committed Nov 11, 2024
1 parent 58f7e70 commit 80f3eff
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
8 changes: 4 additions & 4 deletions rustv1/examples/ec2/src/ec2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand Down
19 changes: 10 additions & 9 deletions rustv1/examples/ec2/src/getting_started/key_pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,26 +47,27 @@ impl KeyPairManager {
util: &Util,
key_name: String,
) -> Result<KeyPairInfo, EC2Error> {
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}")))?;
let (key_pair, material) = ec2.create_key_pair(key_name.clone()).await.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:?})");
Expand Down

0 comments on commit 80f3eff

Please sign in to comment.