Exemplo n.º 1
0
Arquivo: ssh.go Projeto: alexcb/doit
// RunSSH finds a droplet to ssh to given input parameters (name or id).
func RunSSH(ns string, config doit.Config, out io.Writer, args []string) error {
	client := config.GetGodoClient()

	if len(args) == 0 {
		return doit.NewMissingArgsErr(ns)
	}

	dropletID := args[0]

	if dropletID == "" {
		return doit.NewMissingArgsErr(ns)
	}

	user, err := config.GetString(ns, doit.ArgSSHUser)
	if err != nil {
		return err
	}

	keyPath, err := config.GetString(ns, doit.ArgsSSHKeyPath)
	if err != nil {
		return err
	}

	port, err := config.GetInt(ns, doit.ArgsSSHPort)
	if err != nil {
		return err
	}

	var droplet *godo.Droplet

	if id, err := strconv.Atoi(dropletID); err == nil {
		// dropletID is an integer
		droplet, err = getDropletByID(client, id)
	} else {
		// dropletID is a string
		var droplets []godo.Droplet
		droplets, err := listDroplets(client)
		if err != nil {
			return err
		}

		shi := extractHostInfo(dropletID)

		user = shi.user
		if i, err := strconv.Atoi(shi.port); shi.port != "" && err != nil {
			port = i
		}

		for _, d := range droplets {
			if d.Name == shi.host {
				droplet = &d
				break
			}
		}

		if droplet == nil {
			return errors.New("could not find droplet by name")
		}

	}

	if user == "" {
		user = defaultSSHUser(droplet)
	}
	publicIP := extractDropletPublicIP(droplet)

	if len(publicIP) < 1 {
		return errors.New(sshNoAddress)
	}

	runner := config.SSH(user, publicIP, keyPath, port)
	return runner.Run()
}