2015-05-08 23:25:24 +02:00
|
|
|
package chef
|
2015-05-08 13:45:31 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"os"
|
2015-11-24 14:40:46 +01:00
|
|
|
"path"
|
2015-05-08 14:52:25 +02:00
|
|
|
"regexp"
|
2015-05-08 13:45:31 +02:00
|
|
|
"strings"
|
|
|
|
"text/template"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/hashicorp/terraform/communicator"
|
|
|
|
"github.com/hashicorp/terraform/communicator/remote"
|
|
|
|
"github.com/hashicorp/terraform/terraform"
|
2015-06-03 14:45:30 +02:00
|
|
|
"github.com/mitchellh/go-homedir"
|
2015-05-08 13:45:31 +02:00
|
|
|
"github.com/mitchellh/go-linereader"
|
|
|
|
"github.com/mitchellh/mapstructure"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-02-04 15:31:24 +01:00
|
|
|
clienrb = "client.rb"
|
|
|
|
defaultEnv = "_default"
|
|
|
|
firstBoot = "first-boot.json"
|
|
|
|
logfileDir = "logfiles"
|
|
|
|
linuxChefCmd = "chef-client"
|
|
|
|
linuxConfDir = "/etc/chef"
|
2016-09-15 14:20:18 +02:00
|
|
|
linuxNoOutput = "> /dev/null 2>&1"
|
|
|
|
linuxGemCmd = "/opt/chef/embedded/bin/gem"
|
|
|
|
linuxKnifeCmd = "knife"
|
2016-02-04 15:31:24 +01:00
|
|
|
secretKey = "encrypted_data_bag_secret"
|
|
|
|
windowsChefCmd = "cmd /c chef-client"
|
|
|
|
windowsConfDir = "C:/chef"
|
2016-09-15 14:20:18 +02:00
|
|
|
windowsNoOutput = "> nul 2>&1"
|
|
|
|
windowsGemCmd = "C:/opscode/chef/embedded/bin/gem"
|
|
|
|
windowsKnifeCmd = "cmd /c knife"
|
2015-05-08 13:45:31 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const clientConf = `
|
|
|
|
log_location STDOUT
|
|
|
|
chef_server_url "{{ .ServerURL }}"
|
|
|
|
node_name "{{ .NodeName }}"
|
2015-09-26 01:56:24 +02:00
|
|
|
{{ if .UsePolicyfile }}
|
|
|
|
use_policyfile true
|
|
|
|
policy_group "{{ .PolicyGroup }}"
|
|
|
|
policy_name "{{ .PolicyName }}"
|
2016-07-22 16:01:48 +02:00
|
|
|
{{ end -}}
|
2015-09-26 01:56:24 +02:00
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
{{ if .HTTPProxy }}
|
|
|
|
http_proxy "{{ .HTTPProxy }}"
|
|
|
|
ENV['http_proxy'] = "{{ .HTTPProxy }}"
|
|
|
|
ENV['HTTP_PROXY'] = "{{ .HTTPProxy }}"
|
2016-07-22 16:01:48 +02:00
|
|
|
{{ end -}}
|
2015-05-08 13:45:31 +02:00
|
|
|
|
|
|
|
{{ if .HTTPSProxy }}
|
|
|
|
https_proxy "{{ .HTTPSProxy }}"
|
|
|
|
ENV['https_proxy'] = "{{ .HTTPSProxy }}"
|
|
|
|
ENV['HTTPS_PROXY'] = "{{ .HTTPSProxy }}"
|
2016-07-22 16:01:48 +02:00
|
|
|
{{ end -}}
|
2015-05-08 13:45:31 +02:00
|
|
|
|
2016-01-13 15:51:08 +01:00
|
|
|
{{ if .NOProxy }}
|
|
|
|
no_proxy "{{ join .NOProxy "," }}"
|
|
|
|
ENV['no_proxy'] = "{{ join .NOProxy "," }}"
|
2016-07-22 16:01:48 +02:00
|
|
|
{{ end -}}
|
2016-01-13 15:51:08 +01:00
|
|
|
|
2016-07-22 16:01:48 +02:00
|
|
|
{{ if .SSLVerifyMode }}
|
|
|
|
ssl_verify_mode {{ .SSLVerifyMode }}
|
|
|
|
{{- end -}}
|
2016-01-07 18:13:30 +01:00
|
|
|
|
2016-07-22 16:01:48 +02:00
|
|
|
{{ if .DisableReporting }}
|
|
|
|
enable_reporting false
|
|
|
|
{{ end -}}
|
2016-01-09 00:42:02 +01:00
|
|
|
|
2016-07-22 16:01:48 +02:00
|
|
|
{{ if .ClientOptions }}
|
|
|
|
{{ join .ClientOptions "\n" }}
|
|
|
|
{{ end }}
|
2015-05-08 13:45:31 +02:00
|
|
|
`
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
// Provisioner represents a Chef provisioner
|
2015-05-08 13:45:31 +02:00
|
|
|
type Provisioner struct {
|
2016-09-15 14:20:18 +02:00
|
|
|
AttributesJSON string `mapstructure:"attributes_json"`
|
|
|
|
ClientOptions []string `mapstructure:"client_options"`
|
|
|
|
DisableReporting bool `mapstructure:"disable_reporting"`
|
|
|
|
Environment string `mapstructure:"environment"`
|
|
|
|
FetchChefCertificates bool `mapstructure:"fetch_chef_certificates"`
|
|
|
|
LogToFile bool `mapstructure:"log_to_file"`
|
|
|
|
UsePolicyfile bool `mapstructure:"use_policyfile"`
|
|
|
|
PolicyGroup string `mapstructure:"policy_group"`
|
|
|
|
PolicyName string `mapstructure:"policy_name"`
|
|
|
|
HTTPProxy string `mapstructure:"http_proxy"`
|
|
|
|
HTTPSProxy string `mapstructure:"https_proxy"`
|
|
|
|
NOProxy []string `mapstructure:"no_proxy"`
|
|
|
|
NodeName string `mapstructure:"node_name"`
|
|
|
|
OhaiHints []string `mapstructure:"ohai_hints"`
|
|
|
|
OSType string `mapstructure:"os_type"`
|
|
|
|
RecreateClient bool `mapstructure:"recreate_client"`
|
|
|
|
PreventSudo bool `mapstructure:"prevent_sudo"`
|
|
|
|
RunList []string `mapstructure:"run_list"`
|
|
|
|
SecretKey string `mapstructure:"secret_key"`
|
|
|
|
ServerURL string `mapstructure:"server_url"`
|
|
|
|
SkipInstall bool `mapstructure:"skip_install"`
|
|
|
|
SSLVerifyMode string `mapstructure:"ssl_verify_mode"`
|
|
|
|
UserName string `mapstructure:"user_name"`
|
|
|
|
UserKey string `mapstructure:"user_key"`
|
|
|
|
VaultJSON string `mapstructure:"vault_json"`
|
|
|
|
Version string `mapstructure:"version"`
|
|
|
|
|
|
|
|
attributes map[string]interface{}
|
|
|
|
vaults map[string]string
|
|
|
|
|
|
|
|
cleanupUserKeyCmd string
|
2016-02-04 15:31:24 +01:00
|
|
|
createConfigFiles func(terraform.UIOutput, communicator.Communicator) error
|
2016-09-15 14:20:18 +02:00
|
|
|
installChefClient func(terraform.UIOutput, communicator.Communicator) error
|
2016-02-04 15:31:24 +01:00
|
|
|
fetchChefCertificates func(terraform.UIOutput, communicator.Communicator) error
|
2016-09-15 14:20:18 +02:00
|
|
|
generateClientKey func(terraform.UIOutput, communicator.Communicator) error
|
|
|
|
configureVaults func(terraform.UIOutput, communicator.Communicator) error
|
2016-02-04 15:31:24 +01:00
|
|
|
runChefClient func(terraform.UIOutput, communicator.Communicator) error
|
|
|
|
useSudo bool
|
2015-11-12 22:17:51 +01:00
|
|
|
|
|
|
|
// Deprecated Fields
|
2016-09-15 14:20:18 +02:00
|
|
|
ValidationClientName string `mapstructure:"validation_client_name"`
|
|
|
|
ValidationKey string `mapstructure:"validation_key"`
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// ResourceProvisioner represents a generic chef provisioner
|
|
|
|
type ResourceProvisioner struct{}
|
|
|
|
|
|
|
|
// Apply executes the file provisioner
|
|
|
|
func (r *ResourceProvisioner) Apply(
|
|
|
|
o terraform.UIOutput,
|
|
|
|
s *terraform.InstanceState,
|
|
|
|
c *terraform.ResourceConfig) error {
|
|
|
|
// Decode the raw config for this provisioner
|
|
|
|
p, err := r.decodeConfig(c)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-06-25 14:29:48 +02:00
|
|
|
if p.OSType == "" {
|
|
|
|
switch s.Ephemeral.ConnInfo["type"] {
|
|
|
|
case "ssh", "": // The default connection type is ssh, so if the type is empty assume ssh
|
|
|
|
p.OSType = "linux"
|
|
|
|
case "winrm":
|
|
|
|
p.OSType = "windows"
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("Unsupported connection type: %s", s.Ephemeral.ConnInfo["type"])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
// Set some values based on the targeted OS
|
2015-06-25 14:29:48 +02:00
|
|
|
switch p.OSType {
|
|
|
|
case "linux":
|
2016-09-15 14:20:18 +02:00
|
|
|
p.cleanupUserKeyCmd = fmt.Sprintf("rm -f %s", path.Join(linuxConfDir, p.UserName+".pem"))
|
2015-06-25 14:29:48 +02:00
|
|
|
p.createConfigFiles = p.linuxCreateConfigFiles
|
2016-09-15 14:20:18 +02:00
|
|
|
p.installChefClient = p.linuxInstallChefClient
|
2016-02-25 20:10:50 +01:00
|
|
|
p.fetchChefCertificates = p.fetchChefCertificatesFunc(linuxKnifeCmd, linuxConfDir)
|
2016-09-15 14:20:18 +02:00
|
|
|
p.generateClientKey = p.generateClientKeyFunc(linuxKnifeCmd, linuxConfDir, linuxNoOutput)
|
|
|
|
p.configureVaults = p.configureVaultsFunc(linuxGemCmd, linuxKnifeCmd, linuxConfDir)
|
2015-07-10 12:56:27 +02:00
|
|
|
p.runChefClient = p.runChefClientFunc(linuxChefCmd, linuxConfDir)
|
2015-05-12 10:37:38 +02:00
|
|
|
p.useSudo = !p.PreventSudo && s.Ephemeral.ConnInfo["user"] != "root"
|
2015-06-25 14:29:48 +02:00
|
|
|
case "windows":
|
2016-09-15 14:20:18 +02:00
|
|
|
p.cleanupUserKeyCmd = fmt.Sprintf("cd %s && del /F /Q %s", windowsConfDir, p.UserName+".pem")
|
2015-06-25 14:29:48 +02:00
|
|
|
p.createConfigFiles = p.windowsCreateConfigFiles
|
2016-09-15 14:20:18 +02:00
|
|
|
p.installChefClient = p.windowsInstallChefClient
|
2016-02-25 20:10:50 +01:00
|
|
|
p.fetchChefCertificates = p.fetchChefCertificatesFunc(windowsKnifeCmd, windowsConfDir)
|
2016-09-15 14:20:18 +02:00
|
|
|
p.generateClientKey = p.generateClientKeyFunc(windowsKnifeCmd, windowsConfDir, windowsNoOutput)
|
|
|
|
p.configureVaults = p.configureVaultsFunc(windowsGemCmd, windowsKnifeCmd, windowsConfDir)
|
2015-07-10 12:56:27 +02:00
|
|
|
p.runChefClient = p.runChefClientFunc(windowsChefCmd, windowsConfDir)
|
2015-05-12 10:37:38 +02:00
|
|
|
p.useSudo = false
|
2015-05-08 13:45:31 +02:00
|
|
|
default:
|
2015-06-25 14:29:48 +02:00
|
|
|
return fmt.Errorf("Unsupported os type: %s", p.OSType)
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get a new communicator
|
|
|
|
comm, err := communicator.New(s)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait and retry until we establish the connection
|
|
|
|
err = retryFunc(comm.Timeout(), func() error {
|
|
|
|
err := comm.Connect(o)
|
|
|
|
return err
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer comm.Disconnect()
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
// Make sure we always delete the user key from the new node!
|
|
|
|
defer func() {
|
|
|
|
o.Output("Cleanup user key...")
|
|
|
|
if err := p.runCommand(o, comm, p.cleanupUserKeyCmd); err != nil {
|
|
|
|
o.Output("WARNING: Failed to cleanup user key on new node: " + err.Error())
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
if !p.SkipInstall {
|
|
|
|
if err := p.installChefClient(o, comm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
o.Output("Creating configuration files...")
|
|
|
|
if err := p.createConfigFiles(o, comm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-02-04 15:31:24 +01:00
|
|
|
if p.FetchChefCertificates {
|
|
|
|
o.Output("Fetch Chef certificates...")
|
|
|
|
if err := p.fetchChefCertificates(o, comm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
o.Output("Generate the private key...")
|
|
|
|
if err := p.generateClientKey(o, comm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.VaultJSON != "" {
|
|
|
|
o.Output("Configure Chef vaults...")
|
|
|
|
if err := p.configureVaults(o, comm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
o.Output("Starting initial Chef-Client run...")
|
|
|
|
if err := p.runChefClient(o, comm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate checks if the required arguments are configured
|
|
|
|
func (r *ResourceProvisioner) Validate(c *terraform.ResourceConfig) (ws []string, es []error) {
|
|
|
|
p, err := r.decodeConfig(c)
|
|
|
|
if err != nil {
|
|
|
|
es = append(es, err)
|
|
|
|
return ws, es
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.NodeName == "" {
|
2016-09-15 14:20:18 +02:00
|
|
|
es = append(es, errors.New("Key not found: node_name"))
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
2015-10-14 20:05:38 +02:00
|
|
|
if !p.UsePolicyfile && p.RunList == nil {
|
2016-09-15 14:20:18 +02:00
|
|
|
es = append(es, errors.New("Key not found: run_list"))
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
if p.ServerURL == "" {
|
2016-09-15 14:20:18 +02:00
|
|
|
es = append(es, errors.New("Key not found: server_url"))
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
2015-09-26 01:56:24 +02:00
|
|
|
if p.UsePolicyfile && p.PolicyName == "" {
|
2016-09-15 14:20:18 +02:00
|
|
|
es = append(es, errors.New("Policyfile enabled but key not found: policy_name"))
|
2015-09-26 01:56:24 +02:00
|
|
|
}
|
|
|
|
if p.UsePolicyfile && p.PolicyGroup == "" {
|
2016-09-15 14:20:18 +02:00
|
|
|
es = append(es, errors.New("Policyfile enabled but key not found: policy_group"))
|
|
|
|
}
|
|
|
|
if p.UserName == "" && p.ValidationClientName == "" {
|
|
|
|
es = append(es, errors.New(
|
|
|
|
"One of user_name or the deprecated validation_client_name must be provided"))
|
2015-09-26 01:56:24 +02:00
|
|
|
}
|
2016-09-15 14:20:18 +02:00
|
|
|
if p.UserKey == "" && p.ValidationKey == "" {
|
|
|
|
es = append(es, errors.New(
|
|
|
|
"One of user_key or the deprecated validation_key must be provided"))
|
2015-11-12 22:17:51 +01:00
|
|
|
}
|
2016-09-15 14:20:18 +02:00
|
|
|
if p.ValidationClientName != "" {
|
|
|
|
ws = append(ws, "validation_client_name is deprecated, please use user_name instead")
|
2015-11-12 22:17:51 +01:00
|
|
|
}
|
2016-09-15 14:20:18 +02:00
|
|
|
if p.ValidationKey != "" {
|
|
|
|
ws = append(ws, "validation_key is deprecated, please use user_key instead")
|
|
|
|
|
|
|
|
if p.RecreateClient {
|
|
|
|
es = append(es, errors.New(
|
|
|
|
"Cannot use recreate_client=true with the deprecated validation_key, please provide a user_key"))
|
|
|
|
}
|
|
|
|
if p.VaultJSON != "" {
|
|
|
|
es = append(es, errors.New(
|
|
|
|
"Cannot configure chef vaults using the deprecated validation_key, please provide a user_key"))
|
|
|
|
}
|
2016-01-29 18:41:14 +01:00
|
|
|
}
|
2015-05-08 13:45:31 +02:00
|
|
|
|
|
|
|
return ws, es
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *ResourceProvisioner) decodeConfig(c *terraform.ResourceConfig) (*Provisioner, error) {
|
|
|
|
p := new(Provisioner)
|
|
|
|
|
|
|
|
decConf := &mapstructure.DecoderConfig{
|
2015-05-08 23:25:24 +02:00
|
|
|
ErrorUnused: true,
|
2015-05-08 13:45:31 +02:00
|
|
|
WeaklyTypedInput: true,
|
|
|
|
Result: p,
|
|
|
|
}
|
|
|
|
dec, err := mapstructure.NewDecoder(decConf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-08-21 17:26:32 +02:00
|
|
|
// We need to merge both configs into a single map first. Order is
|
|
|
|
// important as we need to make sure interpolated values are used
|
|
|
|
// over raw values. This makes sure that all values are there even
|
|
|
|
// if some still need to be interpolated later on. Without this
|
|
|
|
// the validation will fail when using a variable for a required
|
|
|
|
// parameter (the node_name for example).
|
|
|
|
m := make(map[string]interface{})
|
|
|
|
|
|
|
|
for k, v := range c.Raw {
|
|
|
|
m[k] = v
|
|
|
|
}
|
|
|
|
|
|
|
|
for k, v := range c.Config {
|
|
|
|
m[k] = v
|
2015-06-03 14:45:30 +02:00
|
|
|
}
|
|
|
|
|
2015-08-21 17:26:32 +02:00
|
|
|
if err := dec.Decode(m); err != nil {
|
2015-05-08 13:45:31 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
// Make sure the supplied URL has a trailing slash
|
|
|
|
p.ServerURL = strings.TrimSuffix(p.ServerURL, "/") + "/"
|
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
if p.Environment == "" {
|
2015-05-08 23:27:12 +02:00
|
|
|
p.Environment = defaultEnv
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
2015-06-25 15:48:54 +02:00
|
|
|
for i, hint := range p.OhaiHints {
|
|
|
|
hintPath, err := homedir.Expand(hint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error expanding the path %s: %v", hint, err)
|
|
|
|
}
|
|
|
|
p.OhaiHints[i] = hintPath
|
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
if p.UserName == "" && p.ValidationClientName != "" {
|
|
|
|
p.UserName = p.ValidationClientName
|
2015-07-09 15:05:12 +02:00
|
|
|
}
|
2015-07-09 21:29:27 +02:00
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
if p.UserKey == "" && p.ValidationKey != "" {
|
|
|
|
p.UserKey = p.ValidationKey
|
2016-02-09 11:11:46 +01:00
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
if attrs, ok := c.Config["attributes_json"].(string); ok {
|
2016-02-09 11:11:46 +01:00
|
|
|
var m map[string]interface{}
|
2016-09-15 14:20:18 +02:00
|
|
|
if err := json.Unmarshal([]byte(attrs), &m); err != nil {
|
|
|
|
return nil, fmt.Errorf("Error parsing attributes_json: %v", err)
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
2016-09-15 14:20:18 +02:00
|
|
|
p.attributes = m
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
if vaults, ok := c.Config["vault_json"].(string); ok {
|
|
|
|
var m map[string]string
|
|
|
|
if err := json.Unmarshal([]byte(vaults), &m); err != nil {
|
|
|
|
return nil, fmt.Errorf("Error parsing vault_json: %v", err)
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
2016-09-15 14:20:18 +02:00
|
|
|
p.vaults = m
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
return p, nil
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) deployConfigFiles(
|
|
|
|
o terraform.UIOutput,
|
|
|
|
comm communicator.Communicator,
|
|
|
|
confDir string) error {
|
2016-09-15 14:20:18 +02:00
|
|
|
// Copy the user key to the new instance
|
|
|
|
pk := strings.NewReader(p.UserKey)
|
|
|
|
if err := comm.Upload(path.Join(confDir, p.UserName+".pem"), pk); err != nil {
|
|
|
|
return fmt.Errorf("Uploading user key failed: %v", err)
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
2015-11-12 22:17:51 +01:00
|
|
|
if p.SecretKey != "" {
|
2015-07-09 15:05:12 +02:00
|
|
|
// Copy the secret key to the new instance
|
2016-09-15 14:20:18 +02:00
|
|
|
s := strings.NewReader(p.SecretKey)
|
2015-11-24 14:40:46 +01:00
|
|
|
if err := comm.Upload(path.Join(confDir, secretKey), s); err != nil {
|
2015-07-09 15:05:12 +02:00
|
|
|
return fmt.Errorf("Uploading %s failed: %v", secretKey, err)
|
|
|
|
}
|
2015-07-08 20:43:37 +02:00
|
|
|
}
|
|
|
|
|
2016-07-22 16:01:48 +02:00
|
|
|
// Make sure the SSLVerifyMode value is written as a symbol
|
|
|
|
if p.SSLVerifyMode != "" && !strings.HasPrefix(p.SSLVerifyMode, ":") {
|
|
|
|
p.SSLVerifyMode = fmt.Sprintf(":%s", p.SSLVerifyMode)
|
|
|
|
}
|
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
// Make strings.Join available for use within the template
|
|
|
|
funcMap := template.FuncMap{
|
|
|
|
"join": strings.Join,
|
|
|
|
}
|
|
|
|
|
2015-05-08 23:25:24 +02:00
|
|
|
// Create a new template and parse the client config into it
|
|
|
|
t := template.Must(template.New(clienrb).Funcs(funcMap).Parse(clientConf))
|
2015-05-08 13:45:31 +02:00
|
|
|
|
|
|
|
var buf bytes.Buffer
|
2016-09-15 14:20:18 +02:00
|
|
|
err := t.Execute(&buf, p)
|
2015-05-08 13:45:31 +02:00
|
|
|
if err != nil {
|
2015-05-08 23:25:24 +02:00
|
|
|
return fmt.Errorf("Error executing %s template: %s", clienrb, err)
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
2015-05-08 23:25:24 +02:00
|
|
|
// Copy the client config to the new instance
|
2015-11-24 14:40:46 +01:00
|
|
|
if err := comm.Upload(path.Join(confDir, clienrb), &buf); err != nil {
|
2015-05-08 23:25:24 +02:00
|
|
|
return fmt.Errorf("Uploading %s failed: %v", clienrb, err)
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create a map with first boot settings
|
|
|
|
fb := make(map[string]interface{})
|
2016-09-15 14:20:18 +02:00
|
|
|
if p.attributes != nil {
|
|
|
|
fb = p.attributes
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
2015-05-08 23:25:24 +02:00
|
|
|
// Check if the run_list was also in the attributes and if so log a warning
|
|
|
|
// that it will be overwritten with the value of the run_list argument.
|
|
|
|
if _, found := fb["run_list"]; found {
|
|
|
|
log.Printf("[WARNING] Found a 'run_list' specified in the configured attributes! " +
|
|
|
|
"This value will be overwritten by the value of the `run_list` argument!")
|
|
|
|
}
|
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
// Add the initial runlist to the first boot settings
|
2015-09-26 01:56:24 +02:00
|
|
|
if !p.UsePolicyfile {
|
|
|
|
fb["run_list"] = p.RunList
|
|
|
|
}
|
2015-05-08 13:45:31 +02:00
|
|
|
|
|
|
|
// Marshal the first boot settings to JSON
|
|
|
|
d, err := json.Marshal(fb)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to create %s data: %s", firstBoot, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Copy the first-boot.json to the new instance
|
2015-11-24 14:40:46 +01:00
|
|
|
if err := comm.Upload(path.Join(confDir, firstBoot), bytes.NewReader(d)); err != nil {
|
2015-05-08 23:25:24 +02:00
|
|
|
return fmt.Errorf("Uploading %s failed: %v", firstBoot, err)
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-06-25 15:48:54 +02:00
|
|
|
func (p *Provisioner) deployOhaiHints(
|
|
|
|
o terraform.UIOutput,
|
|
|
|
comm communicator.Communicator,
|
|
|
|
hintDir string) error {
|
|
|
|
for _, hint := range p.OhaiHints {
|
|
|
|
// Open the hint file
|
|
|
|
f, err := os.Open(hint)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
// Copy the hint to the new instance
|
2015-11-24 14:40:46 +01:00
|
|
|
if err := comm.Upload(path.Join(hintDir, path.Base(hint)), f); err != nil {
|
|
|
|
return fmt.Errorf("Uploading %s failed: %v", path.Base(hint), err)
|
2015-06-25 15:48:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
func (p *Provisioner) fetchChefCertificatesFunc(
|
|
|
|
knifeCmd string,
|
|
|
|
confDir string) func(terraform.UIOutput, communicator.Communicator) error {
|
|
|
|
return func(o terraform.UIOutput, comm communicator.Communicator) error {
|
|
|
|
clientrb := path.Join(confDir, clienrb)
|
|
|
|
cmd := fmt.Sprintf("%s ssl fetch -c %s", knifeCmd, clientrb)
|
|
|
|
|
|
|
|
return p.runCommand(o, comm, cmd)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) generateClientKeyFunc(
|
|
|
|
knifeCmd string,
|
|
|
|
confDir string,
|
|
|
|
noOutput string) func(terraform.UIOutput, communicator.Communicator) error {
|
|
|
|
return func(o terraform.UIOutput, comm communicator.Communicator) error {
|
|
|
|
options := fmt.Sprintf("-c %s -u %s --key %s",
|
|
|
|
path.Join(confDir, clienrb),
|
|
|
|
p.UserName,
|
|
|
|
path.Join(confDir, p.UserName+".pem"),
|
|
|
|
)
|
|
|
|
|
|
|
|
// See if we already have a node object
|
|
|
|
getNodeCmd := fmt.Sprintf("%s node show %s %s %s", knifeCmd, p.NodeName, options, noOutput)
|
|
|
|
node := p.runCommand(o, comm, getNodeCmd) == nil
|
|
|
|
|
|
|
|
// See if we already have a client object
|
|
|
|
getClientCmd := fmt.Sprintf("%s client show %s %s %s", knifeCmd, p.NodeName, options, noOutput)
|
|
|
|
client := p.runCommand(o, comm, getClientCmd) == nil
|
|
|
|
|
|
|
|
// If we have a client, we can only continue if we are to recreate the client
|
|
|
|
if client && !p.RecreateClient {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"Chef client %q already exists, set recreate_client=true to automatically recreate the client", p.NodeName)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the node exists, try to delete it
|
|
|
|
if node {
|
|
|
|
deleteNodeCmd := fmt.Sprintf("%s node delete %s -y %s",
|
|
|
|
knifeCmd,
|
|
|
|
p.NodeName,
|
|
|
|
options,
|
|
|
|
)
|
|
|
|
if err := p.runCommand(o, comm, deleteNodeCmd); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the client exists, try to delete it
|
|
|
|
if client {
|
|
|
|
deleteClientCmd := fmt.Sprintf("%s client delete %s -y %s",
|
|
|
|
knifeCmd,
|
|
|
|
p.NodeName,
|
|
|
|
options,
|
|
|
|
)
|
|
|
|
if err := p.runCommand(o, comm, deleteClientCmd); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the new client object
|
|
|
|
createClientCmd := fmt.Sprintf("%s client create %s -d -f %s %s",
|
|
|
|
knifeCmd,
|
|
|
|
p.NodeName,
|
|
|
|
path.Join(confDir, "client.pem"),
|
|
|
|
options,
|
|
|
|
)
|
|
|
|
|
|
|
|
return p.runCommand(o, comm, createClientCmd)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) configureVaultsFunc(
|
|
|
|
gemCmd string,
|
|
|
|
knifeCmd string,
|
|
|
|
confDir string) func(terraform.UIOutput, communicator.Communicator) error {
|
|
|
|
return func(o terraform.UIOutput, comm communicator.Communicator) error {
|
|
|
|
if err := p.runCommand(o, comm, fmt.Sprintf("%s install chef-vault", gemCmd)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
options := fmt.Sprintf("-c %s -u %s --key %s",
|
|
|
|
path.Join(confDir, clienrb),
|
|
|
|
p.UserName,
|
|
|
|
path.Join(confDir, p.UserName+".pem"),
|
|
|
|
)
|
|
|
|
|
|
|
|
for vault, item := range p.vaults {
|
|
|
|
updateCmd := fmt.Sprintf("%s vault update %s %s -A %s -M client %s",
|
|
|
|
knifeCmd,
|
|
|
|
vault,
|
|
|
|
item,
|
|
|
|
p.NodeName,
|
|
|
|
options,
|
|
|
|
)
|
|
|
|
if err := p.runCommand(o, comm, updateCmd); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) runChefClientFunc(
|
|
|
|
chefCmd string,
|
|
|
|
confDir string) func(terraform.UIOutput, communicator.Communicator) error {
|
|
|
|
return func(o terraform.UIOutput, comm communicator.Communicator) error {
|
|
|
|
fb := path.Join(confDir, firstBoot)
|
|
|
|
var cmd string
|
|
|
|
|
|
|
|
// Policyfiles do not support chef environments, so don't pass the `-E` flag.
|
|
|
|
if p.UsePolicyfile {
|
|
|
|
cmd = fmt.Sprintf("%s -j %q", chefCmd, fb)
|
|
|
|
} else {
|
|
|
|
cmd = fmt.Sprintf("%s -j %q -E %q", chefCmd, fb, p.Environment)
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.LogToFile {
|
|
|
|
if err := os.MkdirAll(logfileDir, 0755); err != nil {
|
|
|
|
return fmt.Errorf("Error creating logfile directory %s: %v", logfileDir, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
logFile := path.Join(logfileDir, p.NodeName)
|
|
|
|
f, err := os.Create(path.Join(logFile))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error creating logfile %s: %v", logFile, err)
|
|
|
|
}
|
|
|
|
f.Close()
|
|
|
|
|
|
|
|
o.Output("Writing Chef Client output to " + logFile)
|
|
|
|
o = p
|
|
|
|
}
|
|
|
|
|
|
|
|
return p.runCommand(o, comm, cmd)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Output implementation of terraform.UIOutput interface
|
|
|
|
func (p *Provisioner) Output(output string) {
|
|
|
|
logFile := path.Join(logfileDir, p.NodeName)
|
|
|
|
f, err := os.OpenFile(logFile, os.O_APPEND|os.O_WRONLY, 0666)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error creating logfile %s: %v", logFile, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
// These steps are needed to remove any ANSI escape codes used to colorize
|
|
|
|
// the output and to make sure we have proper line endings before writing
|
|
|
|
// the string to the logfile.
|
|
|
|
re := regexp.MustCompile(`\x1b\[[0-9;]+m`)
|
|
|
|
output = re.ReplaceAllString(output, "")
|
|
|
|
output = strings.Replace(output, "\r", "\n", -1)
|
|
|
|
|
|
|
|
if _, err := f.WriteString(output); err != nil {
|
|
|
|
log.Printf("Error writing output to logfile %s: %v", logFile, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := f.Sync(); err != nil {
|
|
|
|
log.Printf("Error saving logfile %s to disk: %v", logFile, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-08 13:45:31 +02:00
|
|
|
// runCommand is used to run already prepared commands
|
|
|
|
func (p *Provisioner) runCommand(
|
|
|
|
o terraform.UIOutput,
|
|
|
|
comm communicator.Communicator,
|
|
|
|
command string) error {
|
|
|
|
// Unless prevented, prefix the command with sudo
|
2015-05-12 10:37:38 +02:00
|
|
|
if p.useSudo {
|
2015-05-08 13:45:31 +02:00
|
|
|
command = "sudo " + command
|
|
|
|
}
|
|
|
|
|
|
|
|
outR, outW := io.Pipe()
|
|
|
|
errR, errW := io.Pipe()
|
|
|
|
outDoneCh := make(chan struct{})
|
|
|
|
errDoneCh := make(chan struct{})
|
|
|
|
go p.copyOutput(o, outR, outDoneCh)
|
|
|
|
go p.copyOutput(o, errR, errDoneCh)
|
|
|
|
|
|
|
|
cmd := &remote.Cmd{
|
|
|
|
Command: command,
|
|
|
|
Stdout: outW,
|
|
|
|
Stderr: errW,
|
|
|
|
}
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
err := comm.Start(cmd)
|
|
|
|
if err != nil {
|
2015-05-08 13:45:31 +02:00
|
|
|
return fmt.Errorf("Error executing command %q: %v", cmd.Command, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd.Wait()
|
|
|
|
if cmd.ExitStatus != 0 {
|
|
|
|
err = fmt.Errorf(
|
|
|
|
"Command %q exited with non-zero exit status: %d", cmd.Command, cmd.ExitStatus)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for output to clean up
|
|
|
|
outW.Close()
|
|
|
|
errW.Close()
|
|
|
|
<-outDoneCh
|
|
|
|
<-errDoneCh
|
|
|
|
|
2016-09-15 14:20:18 +02:00
|
|
|
return err
|
2015-05-08 13:45:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) copyOutput(o terraform.UIOutput, r io.Reader, doneCh chan<- struct{}) {
|
|
|
|
defer close(doneCh)
|
|
|
|
lr := linereader.New(r)
|
|
|
|
for line := range lr.Ch {
|
|
|
|
o.Output(line)
|
|
|
|
}
|
|
|
|
}
|
2016-09-15 14:20:18 +02:00
|
|
|
|
|
|
|
// retryFunc is used to retry a function for a given duration
|
|
|
|
func retryFunc(timeout time.Duration, f func() error) error {
|
|
|
|
finish := time.After(timeout)
|
|
|
|
for {
|
|
|
|
err := f()
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
log.Printf("Retryable error: %v", err)
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-finish:
|
|
|
|
return err
|
|
|
|
case <-time.After(3 * time.Second):
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|