Skip to content

Commit

Permalink
Add support to delete SSH keys created
Browse files Browse the repository at this point in the history
  • Loading branch information
NotTheEvilOne committed Sep 15, 2021
1 parent c135bb7 commit 043b7b4
Show file tree
Hide file tree
Showing 16 changed files with 84 additions and 17 deletions.
10 changes: 10 additions & 0 deletions pkg/controller/infrastructure/actuator_delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,18 @@ func (a *actuator) delete(ctx context.Context, infra *extensionsv1alpha1.Infrast
return err
}

infraStatus, err := transcoder.DecodeInfrastructureStatusFromInfrastructure(infra)
if err != nil {
return err
}

client := apis.GetClientForToken(string(actuatorConfig.token))

err = ensurer.EnsureSSHPublicKeyDeleted(ctx, client, infraStatus.SSHFingerprint)
if err != nil {
return err
}

err = ensurer.EnsureNetworksDeleted(ctx, client, infra.Namespace, actuatorConfig.infraConfig.Networks)
if err != nil {
return err
Expand Down
3 changes: 2 additions & 1 deletion pkg/controller/infrastructure/actuator_reconcile.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (a *actuator) reconcile(ctx context.Context, infra *extensionsv1alpha1.Infr

client := apis.GetClientForToken(string(actuatorConfig.token))

err = ensurer.EnsureSSHPublicKey(ctx, client, infra.Spec.SSHPublicKey)
sshFingerprint, err := ensurer.EnsureSSHPublicKey(ctx, client, infra.Spec.SSHPublicKey)
if err != nil {
return err
}
Expand All @@ -58,6 +58,7 @@ func (a *actuator) reconcile(ctx context.Context, infra *extensionsv1alpha1.Infr
APIVersion: v1alpha1.SchemeGroupVersion.String(),
Kind: "InfrastructureStatus",
},
SSHFingerprint: sshFingerprint,
}

if "" != infraConfig.FloatingPoolName {
Expand Down
47 changes: 41 additions & 6 deletions pkg/controller/infrastructure/ensurer/ssh_public_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,44 @@ package ensurer

import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"

"github.com/23technologies/gardener-extension-provider-hcloud/pkg/hcloud/apis/transcoder"
"github.com/hetznercloud/hcloud-go/hcloud"
)

func EnsureSSHPublicKey(ctx context.Context, client *hcloud.Client, publicKey []byte) error {
fingerprint, err := transcoder.DecodeSSHFingerprintFromPublicKey(publicKey)
if nil != err {
return err
func EnsureSSHPublicKey(ctx context.Context, client *hcloud.Client, publicKey []byte) (string, error) {
if len(publicKey) == 0 {
return "", fmt.Errorf("SSH public key given is empty")
}

publicKeyData := strings.SplitN(string(publicKey), " ", 3)
if len(publicKeyData) < 2 {
return "", fmt.Errorf("SSH public key has invalid format")
}

publicKey, err := base64.StdEncoding.DecodeString(publicKeyData[1])
if err != nil {
return "", err
}

publicKeyMD5 := md5.Sum(publicKey)
fingerprintArray := make([]string, len(publicKeyMD5))

for i, c := range publicKeyMD5 {
fingerprintArray[i] = hex.EncodeToString([]byte{c})
}

fingerprint := strings.Join(fingerprintArray, ":")

labels := map[string]string{ "hcloud.provider.extensions.gardener.cloud/role": "infrastructure-ssh-v1" }

sshKey, _, err := client.SSHKey.GetByFingerprint(ctx, fingerprint)
if nil != err {
return err
return "", err
} else if sshKey == nil {
opts := hcloud.SSHKeyCreateOpts{
Name: fmt.Sprintf("infrastructure-ssh-%s", fingerprint),
Expand All @@ -44,6 +65,20 @@ func EnsureSSHPublicKey(ctx context.Context, client *hcloud.Client, publicKey []
}

_, _, err := client.SSHKey.Create(ctx, opts)
if nil != err {
return "", err
}
}

return fingerprint, nil
}

func EnsureSSHPublicKeyDeleted(ctx context.Context, client *hcloud.Client, fingerprint string) error {
sshKey, _, err := client.SSHKey.GetByFingerprint(ctx, fingerprint)
if nil != err {
return err
} else if sshKey != nil {
_, err := client.SSHKey.Delete(ctx, sshKey)
if nil != err {
return err
}
Expand Down
12 changes: 4 additions & 8 deletions pkg/controller/worker/machines.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func (w *workerDelegate) DeployMachineClasses(ctx context.Context) error {
return err
}
}

return w.seedChartApplier.Apply(ctx, filepath.Join(hcloud.InternalChartsPath, "machineclass"), w.worker.Namespace, "machineclass", kubernetes.Values(map[string]interface{}{"machineClasses": w.machineClasses}))
}

Expand Down Expand Up @@ -110,11 +111,6 @@ func (w *workerDelegate) generateMachineConfig(ctx context.Context) error {
return err
}

sshFingerprint, err := transcoder.DecodeSSHFingerprintFromPublicKey(w.worker.Spec.SSHPublicKey)
if err != nil {
return err
}

if len(w.worker.Spec.Pools) == 0 {
return fmt.Errorf("missing pool")
}
Expand All @@ -137,18 +133,18 @@ func (w *workerDelegate) generateMachineConfig(ctx context.Context) error {

for _, zone := range pool.Zones {
secretMap := map[string]interface{}{
"userData": string(pool.UserData),
"userData": pool.UserData,
}

for key, value := range machineClassSecretData {
secretMap[key] = string(value)
secretMap[key] = value
}

machineClassSpec := map[string]interface{}{
"cluster": w.worker.Namespace,
"zone": zone,
"imageName": string(imageName),
"sshFingerprint": sshFingerprint,
"sshFingerprint": infraStatus.SSHFingerprint,
"machineType": string(pool.MachineType),
"networkName": fmt.Sprintf("%s-workers", w.worker.Namespace),
"tags": map[string]string{
Expand Down
1 change: 1 addition & 0 deletions pkg/hcloud/apis/config/v1alpha1/zz_generated.conversion.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/hcloud/apis/config/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/hcloud/apis/config/v1alpha1/zz_generated.defaults.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/hcloud/apis/config/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions pkg/hcloud/apis/mock/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ limitations under the License.
package mock

import (
"fmt"
"net/http"
"regexp"
"strconv"
Expand All @@ -31,9 +32,10 @@ import (
)

const (
TestWorkerInfrastructureProviderStatus = `{
TestWorkerInfrastructureProviderStatusTemplate = `{
"apiVersion": "hcloud.provider.extensions.gardener.cloud/v1alpha1",
"kind": "InfrastructureStatus",
"sshFingerprint": %q,
"floatingPoolName": "MY-FLOATING-POOL"
}`
TestWorkerMachineImageName = "ubuntu"
Expand All @@ -59,7 +61,7 @@ func NewWorker() *v1alpha1.Worker {
},
Region: TestRegion,
InfrastructureProviderStatus: &runtime.RawExtension{
Raw: []byte(TestWorkerInfrastructureProviderStatus),
Raw: []byte(fmt.Sprintf(TestWorkerInfrastructureProviderStatusTemplate, TestSSHFingerprint)),
},
Pools: []v1alpha1.WorkerPool{
{
Expand Down
9 changes: 9 additions & 0 deletions pkg/hcloud/apis/transcoder/infrastructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,12 @@ func DecodeInfrastructureStatus(infra *runtime.RawExtension) (*apis.Infrastructu

return infraStatus, nil
}

func DecodeInfrastructureStatusFromInfrastructure(infra *v1alpha1.Infrastructure) (*apis.InfrastructureStatus, error) {
infraStatus, err := DecodeInfrastructureStatus(infra.Status.ProviderStatus)
if err != nil {
return nil, err
}

return infraStatus, nil
}
2 changes: 2 additions & 0 deletions pkg/hcloud/apis/types_infrastructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ type Networks struct {
// InfrastructureStatus contains information about created infrastructure resources.
type InfrastructureStatus struct {
metav1.TypeMeta `json:",inline"`
// SSHFingerprint contains the SSH fingerprint.
SSHFingerprint string `json:"sshFingerprint,omitempty"`

// FloatingPoolName contains the FloatingPoolName name in which LoadBalancer FIPs should be created.
// +optional
Expand Down
2 changes: 2 additions & 0 deletions pkg/hcloud/apis/v1alpha1/types_infrastructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ type Networks struct {
// InfrastructureStatus contains information about created infrastructure resources.
type InfrastructureStatus struct {
metav1.TypeMeta `json:",inline"`
// SSHFingerprint contains the SSH fingerprint.
SSHFingerprint string `json:"sshFingerprint,omitempty"`

// FloatingPoolName contains the FloatingPoolName name in which LoadBalancer FIPs should be created.
// +optional
Expand Down
3 changes: 3 additions & 0 deletions pkg/hcloud/apis/v1alpha1/zz_generated.conversion.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/hcloud/apis/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/hcloud/apis/v1alpha1/zz_generated.defaults.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/hcloud/apis/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 043b7b4

Please sign in to comment.