diff --git a/pkg/cluster/action_apply.go b/pkg/cluster/action_apply.go index 19388308..19e8f10b 100644 --- a/pkg/cluster/action_apply.go +++ b/pkg/cluster/action_apply.go @@ -5,6 +5,7 @@ import ( "os" "path" "path/filepath" + "strings" "github.com/MusicDin/kubitect/embed" "github.com/MusicDin/kubitect/pkg/cluster/event" @@ -312,6 +313,13 @@ func (c *Cluster) generateSshKeys() error { // - Check if the user has provided a custom path to the key pair pkPath := string(c.NewConfig.Cluster.NodeTemplate.SSH.PrivateKeyPath) if pkPath != "" { + homeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("keygen: %v", err) + } + + pkPath = strings.Replace(pkPath, "~", homeDir, 1) + kp, err := keygen.ReadKeyPair(path.Dir(pkPath), path.Base(pkPath)) if err != nil { return err diff --git a/pkg/cluster/action_apply_test.go b/pkg/cluster/action_apply_test.go index ccb666a6..e0504134 100644 --- a/pkg/cluster/action_apply_test.go +++ b/pkg/cluster/action_apply_test.go @@ -2,6 +2,7 @@ package cluster import ( "os" + "path" "testing" "time" @@ -9,6 +10,7 @@ import ( "github.com/MusicDin/kubitect/pkg/models/config" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestToApplyAction(t *testing.T) { @@ -66,6 +68,23 @@ func TestGenerateMissingKeys_PKPathProvided(t *testing.T) { assert.NoError(t, c.generateSshKeys()) } +func TestGenerateMissingKeys_PKPathProvidedWithTilde(t *testing.T) { + c := MockCluster(t) + + oldHome := os.Getenv("HOME") + defer func() { require.NoError(t, os.Setenv("HOME", oldHome)) }() + + homeDir := t.TempDir() + keyDir := path.Join(homeDir, ".ssh") + require.NoError(t, os.MkdirAll(keyDir, 0755)) + require.NoError(t, os.WriteFile(path.Join(keyDir, "id_rsa"), []byte("private"), 0600)) + require.NoError(t, os.WriteFile(path.Join(keyDir, "id_rsa.pub"), []byte("public"), 0600)) + require.NoError(t, os.Setenv("HOME", homeDir)) + + c.NewConfig.Cluster.NodeTemplate.SSH.PrivateKeyPath = "~/.ssh/id_rsa" + assert.NoError(t, c.generateSshKeys()) +} + func TestPrepare(t *testing.T) { c := MockLocalCluster(t) assert.NoError(t, c.prepare())