/
sshAutomateHA.go
364 lines (333 loc) · 11.2 KB
/
sshAutomateHA.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package main
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
dc "github.com/chef/automate/api/config/deployment"
"github.com/chef/automate/components/automate-cli/pkg/docs"
"github.com/chef/automate/components/automate-cli/pkg/status"
"github.com/spf13/cobra"
)
var automateHATerraformOutputFile = "/hab/a2_deploy_workspace/terraform/terraform.tfstate"
var automateHATerraformDestroyOutputFile = "/hab/a2_deploy_workspace/terraform/destroy/aws/terraform.tfstate"
var sshFlags = struct {
hostname string
}{}
type AutomateHAInfraDetails struct {
Version int `json:"version"`
TerraformVersion string `json:"terraform_version"`
Serial int `json:"serial"`
Lineage string `json:"lineage"`
Outputs struct {
AutomateAdminPassword struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"automate_admin_password"`
AutomateAdminUser struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"automate_admin_user"`
AutomateDataCollectorToken struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"automate_data_collector_token"`
AutomateFrontendUrls struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"automate_frontend_url"`
AutomatePrivateIps struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"automate_private_ips"`
AutomatePublicIps struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"automate_public_ips"`
AutomateSSH struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"automate_ssh"`
AutomateURL struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"automate_url"`
ChefServerPrivateIps struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"chef_server_private_ips"`
ChefServerPublicIps struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"chef_server_public_ips"`
ChefServerSSH struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"chef_server_ssh"`
OpensearchPrivateIps struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"opensearch_private_ips"`
OpensearchSSH struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"opensearch_ssh"`
OpsDashboardAddresses struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"ops_dashboard_addresses"`
PostgresqlPrivateIps struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"postgresql_private_ips"`
PostgresqlPublicIps struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"postgresql_public_ips"`
PostgresqlSSH struct {
Value []string `json:"value"`
Type []string `json:"type"`
} `json:"postgresql_ssh"`
SSHKeyFile struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"ssh_key_file"`
SSHUser struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"ssh_user"`
SSHPort struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"ssh_port"`
BackupConfigEFS struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"backup_config_efs"`
BackupConfigS3 struct {
Value string `json:"value"`
Type string `json:"type"`
} `json:"backup_config_s3"`
} `json:"outputs"`
Resources []struct {
Module string `json:"module,omitempty"`
Mode string `json:"mode"`
Type string `json:"type"`
Name string `json:"name"`
Provider string `json:"provider"`
Instances []struct {
SchemaVersion int `json:"schema_version"`
Attributes struct {
Architecture string `json:"architecture"`
Arn string `json:"arn"`
BlockDeviceMappings []struct {
DeviceName string `json:"device_name"`
Ebs struct {
DeleteOnTermination string `json:"delete_on_termination"`
Encrypted string `json:"encrypted"`
Iops string `json:"iops"`
SnapshotID string `json:"snapshot_id"`
Throughput string `json:"throughput"`
VolumeSize string `json:"volume_size"`
VolumeType string `json:"volume_type"`
} `json:"ebs"`
NoDevice string `json:"no_device"`
VirtualName string `json:"virtual_name"`
} `json:"block_device_mappings"`
CreationDate time.Time `json:"creation_date"`
Description string `json:"description"`
EnaSupport bool `json:"ena_support"`
ExecutableUsers interface{} `json:"executable_users"`
Filter []struct {
Name string `json:"name"`
Values []string `json:"values"`
} `json:"filter"`
Hypervisor string `json:"hypervisor"`
ID string `json:"id"`
ImageID string `json:"image_id"`
ImageLocation string `json:"image_location"`
ImageOwnerAlias interface{} `json:"image_owner_alias"`
ImageType string `json:"image_type"`
KernelID interface{} `json:"kernel_id"`
MostRecent bool `json:"most_recent"`
Name string `json:"name"`
NameRegex interface{} `json:"name_regex"`
OwnerID string `json:"owner_id"`
Owners []string `json:"owners"`
Platform interface{} `json:"platform"`
PlatformDetails string `json:"platform_details"`
ProductCodes []interface{} `json:"product_codes"`
Public bool `json:"public"`
RamdiskID interface{} `json:"ramdisk_id"`
RootDeviceName string `json:"root_device_name"`
RootDeviceType string `json:"root_device_type"`
RootSnapshotID string `json:"root_snapshot_id"`
SriovNetSupport string `json:"sriov_net_support"`
State string `json:"state"`
StateReason struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"state_reason"`
Tags struct {
} `json:"tags"`
UsageOperation string `json:"usage_operation"`
VirtualizationType string `json:"virtualization_type"`
} `json:"attributes"`
} `json:"instances"`
Each string `json:"each,omitempty"`
} `json:"resources"`
}
func init() {
sshCommand.PersistentFlags().StringVarP(
&sshFlags.hostname,
"hostname",
"H",
"",
"Automate ha server name to ssh")
RootCmd.AddCommand(sshCommand)
}
var sshCommand = &cobra.Command{
Use: "ssh",
Short: "SSH into Automate HA servers",
Long: "SSH into Automate HA servers",
Annotations: map[string]string{
NoCheckVersionAnnotation: NoCheckVersionAnnotation,
docs.Compatibility: docs.CompatiblewithHA,
},
RunE: runSshCommand,
}
func runSshCommand(_ *cobra.Command, _ []string) error {
if !isA2HARBFileExist() {
return errors.New(AUTOMATE_HA_INVALID_BASTION)
}
infra, err := getAutomateHAInfraDetails()
if err != nil {
return err
}
sshStrings, err := getIPOfRequestedServers(sshFlags.hostname, infra)
if err != nil {
return err
}
idx, err := writer.Prompt(strings.Join(sshStrings, "\n") + "\n press 1 to " + strconv.Itoa(len(sshStrings)))
if err != nil {
return err
}
i, err := strconv.Atoi(idx)
if err != nil {
return err
}
if i < 1 || i > len(sshStrings) {
return errors.New("invalid input it should be between 1 to " + strconv.Itoa(len(sshStrings)))
}
var sshString string = sshStrings[i-1]
sshTokens := strings.Split(sshString, " ")
return executeShellCommand(sshTokens[0], sshTokens[1:], "")
}
func getAutomateHAInfraDetails() (*AutomateHAInfraDetails, error) {
infraConfigFile, err := FileContainingAutomateHAInfraDetails()
if err != nil {
return nil, err
}
return getAutomateHAInfraDetailHelper(infraConfigFile)
}
func getAutomateHAInfraDetailHelper(infraConfigFilePath string) (*AutomateHAInfraDetails, error) {
automateHAInfraDetails := &AutomateHAInfraDetails{}
file, err := os.Open(infraConfigFilePath)
if err != nil {
return nil, err
}
defer file.Close()
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(file)
if err != nil {
return nil, err
}
content := buf.String()
if content == "" {
return nil, errors.New("the file is empty")
}
err = json.Unmarshal([]byte(content), automateHAInfraDetails)
if err != nil {
return nil, err
}
extractPortAndSshUserFromAutomateSSHCommand(automateHAInfraDetails)
return automateHAInfraDetails, nil
}
func FileContainingAutomateHAInfraDetails() (string, error) {
if _, err := os.Stat(automateHATerraformOutputFile); errors.Is(err, nil) {
return automateHATerraformOutputFile, nil
}
if _, err := os.Stat(automateHATerraformDestroyOutputFile); errors.Is(err, nil) {
return automateHATerraformDestroyOutputFile, nil
}
return "", errors.New("Automate Ha infra confile file not exist")
}
func extractPortAndSshUserFromAutomateSSHCommand(automateHAInfraDetails *AutomateHAInfraDetails) {
if automateHAInfraDetails == nil || len(automateHAInfraDetails.Outputs.AutomateSSH.Value) == 0 {
return
}
automateSSH := automateHAInfraDetails.Outputs.AutomateSSH.Value[0]
lastSpaceIndex := strings.LastIndex(automateSSH, " ")
if len(strings.TrimSpace(automateHAInfraDetails.Outputs.SSHPort.Value)) == 0 {
port := getSSHPortFromAutomateSSH(automateSSH, lastSpaceIndex)
automateHAInfraDetails.Outputs.SSHPort.Value = port
}
if len(strings.TrimSpace(automateHAInfraDetails.Outputs.SSHUser.Value)) == 0 {
sshUser := strings.TrimSpace(automateSSH[lastSpaceIndex:strings.LastIndex(automateSSH, "@")])
automateHAInfraDetails.Outputs.SSHUser.Value = sshUser
}
}
func getSSHPortFromAutomateSSH(automateSSH string, lastSpaceIndex int) string {
port := "22"
if strings.Contains(automateSSH, "-p") {
port = strings.TrimSpace(automateSSH[strings.LastIndex(automateSSH, "-p")+2 : lastSpaceIndex])
}
return port
}
func getIPOfRequestedServers(servername string, d *AutomateHAInfraDetails) ([]string, error) {
isManagedServices := isManagedServicesOn()
switch strings.ToLower(servername) {
case "automate", "a2":
return d.Outputs.AutomateSSH.Value, nil
case "chef_server", "cs":
return d.Outputs.ChefServerSSH.Value, nil
case "postgresql", "pg":
if isManagedServices {
return d.Outputs.PostgresqlSSH.Value, status.Annotate(errors.New("can not ssh managed service"), status.InvalidCommandArgsError)
}
return d.Outputs.PostgresqlSSH.Value, nil
case "opensearch", "os":
if isManagedServices {
return d.Outputs.OpensearchSSH.Value, errors.New("can not ssh managed service")
}
return d.Outputs.OpensearchSSH.Value, nil
default:
return nil, errors.New("invalid hostname possible values should be any one of automate/a2, chef_server/cs, postgresql/pg or opensearch/os")
}
}
func getPostgresOrOpenSearchExistingLogConfig(remoteType string) (*dc.AutomateConfig, error) {
var log dc.AutomateConfig
var fileName string
if remoteType == "postgresql" {
fileName = postgresLogConfig
} else {
fileName = opensearchConfig
}
if checkIfFileExist(fileName) {
contents, err := ioutil.ReadFile(fileName) // nosemgrep
if err != nil {
return nil, err
}
destString := string(contents)
log1, err := decodeLogConfig(destString)
log = *log1
if err != nil {
return &log, err
}
}
return &log, nil
}