This repository has been archived by the owner on Jul 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
ssh.go
197 lines (170 loc) · 6.7 KB
/
ssh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
"github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"
mcmv1alpha1 "github.com/gardener/machine-controller-manager/pkg/client/clientset/versioned"
"github.com/spf13/cobra"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
)
var (
flagproviderid string
)
const (
// warningColor prints user warnings in red
warningColor = "\033[1;31m%s\033[0m"
// user is operating system user for bastion host and instances
user = "gardener"
)
// NewSSHCmd returns a new ssh command.
func NewSSHCmd(targetReader TargetReader, ioStreams IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "ssh",
Short: "SSH to a node, .e.g. \"gardenctl ssh node_name\"",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
target := targetReader.ReadTarget(pathTarget)
if !CheckShootIsTargeted(target) {
return errors.New("no shoot targeted")
}
shoot, err := FetchShootFromTarget(target)
checkError(err)
if len(args) == 0 && flagproviderid == "" {
return printNodeNames(targetReader, shoot.Name)
}
path := downloadTerraformFiles("infra", targetReader)
if path != "" {
path = filepath.Join(path, "terraform.tfstate")
}
// warning: entering untrusted zone
fmt.Printf(warningColor, "\nWarning:\nBe aware that you are entering an untrusted environment!\nDo not enter credentials or sensitive data within the ssh session that cluster owners should not have access to.\n")
fmt.Println("")
gardenName := target.Stack()[0].Name
shootName := target.Stack()[2].Name
var pathSSKeypair string
if target.Stack()[1].Kind == TargetKindProject {
projectName := target.Stack()[1].Name
pathSSKeypair = filepath.Join(pathGardenHome, "cache", gardenName, "projects", projectName, shootName)
} else {
seedName := target.Stack()[1].Name
pathSSKeypair = filepath.Join(pathGardenHome, "cache", gardenName, "seeds", seedName, shootName)
}
sshKeypairSecret := getSSHKeypair(shoot)
checkError(err)
err = ioutil.WriteFile(filepath.Join(pathSSKeypair, "key"), sshKeypairSecret.Data["id_rsa"], 0600)
checkError(err)
fmt.Println("Downloaded id_rsa key")
fmt.Println("Check Public IP")
myPublicIP := getPublicIP()
sshPublicKey := sshKeypairSecret.Data["id_rsa.pub"]
infraType := shoot.Spec.Provider.Type
switch infraType {
case "aws":
if flagproviderid != "" {
sshToAWSNode(targetReader, "", path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
} else {
sshToAWSNode(targetReader, args[0], path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
}
case "gcp":
if flagproviderid != "" {
sshToGCPNode(targetReader, "", path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
} else {
sshToGCPNode(targetReader, args[0], path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
}
case "azure":
if flagproviderid != "" {
sshToAZNode(targetReader, "", path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
} else {
sshToAZNode(targetReader, args[0], path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
}
case "alicloud":
if flagproviderid != "" {
sshToAlicloudNode(targetReader, "", path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
} else {
sshToAlicloudNode(targetReader, args[0], path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
}
case "openstack":
if flagproviderid != "" {
sshToOpenstackNode("", path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
} else {
sshToOpenstackNode(args[0], path, user, pathSSKeypair, sshPublicKey, myPublicIP, flagproviderid)
}
default:
return fmt.Errorf("infrastructure type %q not found", infraType)
}
return nil
},
}
cmd.PersistentFlags().StringVarP(&flagproviderid, "providerid", "p", "", "machine provider id")
return cmd
}
// getSSHKeypair downloads ssh keypair for a shoot cluster
func getSSHKeypair(shoot *gardencorev1beta1.Shoot) *v1.Secret {
Client, err := clientToTarget("garden")
checkError(err)
secret, err := Client.CoreV1().Secrets(shoot.Namespace).Get(shoot.Name+".ssh-keypair", metav1.GetOptions{})
checkError(err)
return secret
}
// printNodeNames print all nodes in k8s cluster
func printNodeNames(targetReader TargetReader, shootName string) error {
machineList, err := getMachineList(targetReader, shootName)
checkError(err)
fmt.Println("Nodes:")
for _, machine := range machineList.Items {
fmt.Printf("%s (%s)", machine.Status.Node, string(machine.Status.CurrentStatus.Phase))
}
return nil
}
func getBastionUserData(sshPublicKey []byte) []byte {
template := `#!/bin/bash -eu
id gardener || useradd gardener -mU
mkdir -p /home/gardener/.ssh
echo %q > /home/gardener/.ssh/authorized_keys
chown gardener:gardener /home/gardener/.ssh/authorized_keys
echo "gardener ALL=(ALL) NOPASSWD:ALL" >/etc/sudoers.d/99-gardener-user
`
userData := fmt.Sprintf(template, sshPublicKey)
return []byte(userData)
}
func getMachineList(targetReader TargetReader, shootName string) (*v1alpha1.MachineList, error) {
if getRole(targetReader) == "user" {
var target Target
ReadTarget(pathTarget, &target)
clientset, err := target.K8SClientToKind("shoot")
checkError(err)
fmt.Printf("%s\n", "Nodes")
list, _ := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
for _, node := range list.Items {
fmt.Printf("%s\n", node.Name)
}
os.Exit(0)
}
config, err := clientcmd.BuildConfigFromFlags("", getKubeConfigOfClusterType("seed"))
checkError(err)
client, err := mcmv1alpha1.NewForConfig(config)
checkError(err)
shootNamespace := getSeedNamespaceNameForShoot(shootName)
machines, err := client.MachineV1alpha1().Machines(shootNamespace).List(metav1.ListOptions{})
checkError(err)
return machines, nil
}