github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/environs/manual/sshprovisioner/provisioner.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Copyright 2016 Cloudbase Solutions SRL
     3  // Licensed under the AGPLv3, see LICENCE file for details.
     4  
     5  package sshprovisioner
     6  
     7  import (
     8  	"github.com/juju/loggo"
     9  
    10  	"github.com/juju/juju/apiserver/params"
    11  	"github.com/juju/juju/environs/manual"
    12  )
    13  
    14  var (
    15  	logger = loggo.GetLogger("juju.environs.manual.sshprovisioner")
    16  )
    17  
    18  // Provision returns a new machineId and nil if the provision process is done successfully
    19  // The func will manual provision a linux machine using as it's default protocol SSH
    20  func ProvisionMachine(args manual.ProvisionMachineArgs) (machineId string, err error) {
    21  	defer func() {
    22  		if machineId != "" && err != nil {
    23  			logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err)
    24  			if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil {
    25  				logger.Errorf("error cleaning up machine: %s", cleanupErr)
    26  			}
    27  			machineId = ""
    28  		}
    29  	}()
    30  
    31  	// Create the "ubuntu" user and initialise passwordless sudo. We populate
    32  	// the ubuntu user's authorized_keys file with the public keys in the current
    33  	// user's ~/.ssh directory. The authenticationworker will later update the
    34  	// ubuntu user's authorized_keys.
    35  	if err = InitUbuntuUser(args.Host, args.User,
    36  		args.AuthorizedKeys, args.Stdin, args.Stdout); err != nil {
    37  		return "", err
    38  	}
    39  
    40  	machineParams, err := gatherMachineParams(args.Host)
    41  	if err != nil {
    42  		return "", err
    43  	}
    44  
    45  	// Inform Juju that the machine exists.
    46  	machineId, err = manual.RecordMachineInState(args.Client, *machineParams)
    47  	if err != nil {
    48  		return "", err
    49  	}
    50  
    51  	provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{
    52  		MachineId:              machineId,
    53  		Nonce:                  machineParams.Nonce,
    54  		DisablePackageCommands: !args.EnableOSRefreshUpdate && !args.EnableOSUpgrade,
    55  	})
    56  
    57  	if err != nil {
    58  		logger.Errorf("cannot obtain provisioning script")
    59  		return "", err
    60  	}
    61  
    62  	// Finally, provision the machine agent.
    63  	err = runProvisionScript(provisioningScript, args.Host, args.Stderr)
    64  	if err != nil {
    65  		return machineId, err
    66  	}
    67  
    68  	logger.Infof("Provisioned machine %v", machineId)
    69  	return machineId, nil
    70  }