Skip to content

Commit

Permalink
feat: add ability to check for multiple default ssh key locations
Browse files Browse the repository at this point in the history
Since Ubuntu 24.04 LTS and newer, the default location for ssh keys is
`~/.ssh/id_ed25519` instead of `~/.ssh/id_rsa`. Thus, when no ssh key
path is specified, this commit changes pycloudlib to check for an
existing ssh key at either  `~/.ssh/id_ed25519` or `~/.ssh/id_rsa`.

Fixes GH canonical#341
  • Loading branch information
a-dubs committed Sep 24, 2024
1 parent c468a92 commit e540971
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1!9.3.2
1!9.4.0
44 changes: 37 additions & 7 deletions pycloudlib/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
import paramiko

from pycloudlib.config import ConfigFile, parse_config
from pycloudlib.errors import CleanupError, InvalidTagNameError
from pycloudlib.errors import (
CleanupError,
InvalidTagNameError,
PycloudlibError,
)
from pycloudlib.instance import BaseInstance
from pycloudlib.key import KeyPair
from pycloudlib.util import (
Expand Down Expand Up @@ -62,13 +66,39 @@ def __init__(
self._check_and_set_config(config_file, required_values)

user = getpass.getuser()
# check if id_rsa or id_ed25519 keys exist in the user's .ssh directory
possible_default_keys = [
os.path.expanduser("~/.ssh/id_rsa.pub"),
os.path.expanduser("~/.ssh/id_ed25519.pub"),
]
public_key_path: Optional[str] = os.path.expanduser(
self.config.get("public_key_path", "")
)
if not public_key_path:
for pubkey in possible_default_keys:
if os.path.exists(pubkey):
self._log.debug(
"No public key path provided, using: %s", pubkey
)
public_key_path = pubkey
break
if not public_key_path:
raise PycloudlibError(
"No public key path provided and no key found in default locations: "
"'~/.ssh/id_rsa.pub' or '~/.ssh/id_ed25519.pub'"
)
if not os.path.exists(os.path.expanduser(public_key_path)):
raise PycloudlibError(
f"Provided public key path '{public_key_path}' does not exist"
)
if public_key_path not in possible_default_keys:
self._log.debug(
"Using provided public key path: '%s'", public_key_path
)
private_key_path = self.config.get("private_key_path", "")
self.key_pair = KeyPair(
public_key_path=os.path.expandvars(
self.config.get("public_key_path", f"~{user}/.ssh/id_rsa.pub")
),
private_key_path=os.path.expandvars(
self.config.get("private_key_path", "")
),
public_key_path=public_key_path,
private_key_path=private_key_path,
name=self.config.get("key_name", user),
)

Expand Down

0 comments on commit e540971

Please sign in to comment.