feat: pre command for ssh deploy

This commit is contained in:
Madray Haven
2024-09-27 15:12:04 +08:00
parent 38d975a3bb
commit 9acdd15c1e
4 changed files with 54 additions and 17 deletions

View File

@@ -19,14 +19,15 @@ type ssh struct {
}
type sshAccess struct {
Host string `json:"host"`
Username string `json:"username"`
Password string `json:"password"`
Key string `json:"key"`
Port string `json:"port"`
Command string `json:"command"`
CertPath string `json:"certPath"`
KeyPath string `json:"keyPath"`
Host string `json:"host"`
Username string `json:"username"`
Password string `json:"password"`
Key string `json:"key"`
Port string `json:"port"`
PreCommand string `json:"preCommand"`
Command string `json:"command"`
CertPath string `json:"certPath"`
KeyPath string `json:"keyPath"`
}
func NewSSH(option *DeployerOption) (Deployer, error) {
@@ -56,6 +57,7 @@ func (s *ssh) Deploy(ctx context.Context) error {
access.CertPath = strings.ReplaceAll(access.CertPath, key, v)
access.KeyPath = strings.ReplaceAll(access.KeyPath, key, v)
access.Command = strings.ReplaceAll(access.Command, key, v)
access.PreCommand = strings.ReplaceAll(access.PreCommand, key, v)
}
// 连接
@@ -67,14 +69,24 @@ func (s *ssh) Deploy(ctx context.Context) error {
s.infos = append(s.infos, toStr("ssh连接成功", nil))
// 上传
session, err := client.NewSession()
if err != nil {
return fmt.Errorf("failed to create session: %w", err)
}
defer session.Close()
// 执行前置命令
if access.PreCommand != "" {
session, err := client.NewSession()
if err != nil {
return fmt.Errorf("failed to create session: %w", err)
}
defer session.Close()
var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf
var stderrBuf bytes.Buffer
session.Stderr = &stderrBuf
s.infos = append(s.infos, toStr("ssh创建session成功", nil))
s.infos = append(s.infos, toStr("ssh为前置命令创建session成功", nil))
if err := session.Run(access.PreCommand); err != nil {
return fmt.Errorf("failed to run pre-command: %w, stdout: %s, stderr: %s", err, stdoutBuf.String(), stderrBuf.String())
}
}
// 上传证书
if err := s.upload(client, s.option.Certificate.Certificate, access.CertPath); err != nil {
@@ -91,11 +103,16 @@ func (s *ssh) Deploy(ctx context.Context) error {
s.infos = append(s.infos, toStr("ssh上传私钥成功", nil))
// 执行命令
session, err := client.NewSession()
if err != nil {
return fmt.Errorf("failed to create session: %w", err)
}
defer session.Close()
var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf
var stderrBuf bytes.Buffer
session.Stderr = &stderrBuf
s.infos = append(s.infos, toStr("ssh创建session成功", nil))
if err := session.Run(access.Command); err != nil {
return fmt.Errorf("failed to run command: %w, stdout: %s, stderr: %s", err, stdoutBuf.String(), stderrBuf.String())
}