forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provisioner.go
538 lines (457 loc) · 12.9 KB
/
provisioner.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
package ansible
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"unicode"
"golang.org/x/crypto/ssh"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/template/interpolate"
)
type Config struct {
common.PackerConfig `mapstructure:",squash"`
ctx interpolate.Context
// The command to run ansible
Command string
// Extra options to pass to the ansible command
ExtraArguments []string `mapstructure:"extra_arguments"`
AnsibleEnvVars []string `mapstructure:"ansible_env_vars"`
// The main playbook file to execute.
PlaybookFile string `mapstructure:"playbook_file"`
Groups []string `mapstructure:"groups"`
EmptyGroups []string `mapstructure:"empty_groups"`
HostAlias string `mapstructure:"host_alias"`
User string `mapstructure:"user"`
LocalPort string `mapstructure:"local_port"`
SSHHostKeyFile string `mapstructure:"ssh_host_key_file"`
SSHAuthorizedKeyFile string `mapstructure:"ssh_authorized_key_file"`
SFTPCmd string `mapstructure:"sftp_command"`
SkipVersionCheck bool `mapstructure:"skip_version_check"`
UseSFTP bool `mapstructure:"use_sftp"`
InventoryDirectory string `mapstructure:"inventory_directory"`
inventoryFile string
}
type Provisioner struct {
config Config
adapter *adapter
done chan struct{}
ansibleVersion string
ansibleMajVersion uint
}
func (p *Provisioner) Prepare(raws ...interface{}) error {
p.done = make(chan struct{})
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
if err != nil {
return err
}
// Defaults
if p.config.Command == "" {
p.config.Command = "ansible-playbook"
}
if p.config.HostAlias == "" {
p.config.HostAlias = "default"
}
var errs *packer.MultiError
err = validateFileConfig(p.config.PlaybookFile, "playbook_file", true)
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
// Check that the authorized key file exists
if len(p.config.SSHAuthorizedKeyFile) > 0 {
err = validateFileConfig(p.config.SSHAuthorizedKeyFile, "ssh_authorized_key_file", true)
if err != nil {
log.Println(p.config.SSHAuthorizedKeyFile, "does not exist")
errs = packer.MultiErrorAppend(errs, err)
}
}
if len(p.config.SSHHostKeyFile) > 0 {
err = validateFileConfig(p.config.SSHHostKeyFile, "ssh_host_key_file", true)
if err != nil {
log.Println(p.config.SSHHostKeyFile, "does not exist")
errs = packer.MultiErrorAppend(errs, err)
}
} else {
p.config.AnsibleEnvVars = append(p.config.AnsibleEnvVars, "ANSIBLE_HOST_KEY_CHECKING=False")
}
if !p.config.UseSFTP {
p.config.AnsibleEnvVars = append(p.config.AnsibleEnvVars, "ANSIBLE_SCP_IF_SSH=True")
}
if len(p.config.LocalPort) > 0 {
if _, err := strconv.ParseUint(p.config.LocalPort, 10, 16); err != nil {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("local_port: %s must be a valid port", p.config.LocalPort))
}
} else {
p.config.LocalPort = "0"
}
if len(p.config.InventoryDirectory) > 0 {
err = validateInventoryDirectoryConfig(p.config.InventoryDirectory)
if err != nil {
log.Println(p.config.InventoryDirectory, "does not exist")
errs = packer.MultiErrorAppend(errs, err)
}
}
if !p.config.SkipVersionCheck {
err = p.getVersion()
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
if p.config.User == "" {
p.config.User = os.Getenv("USER")
}
if p.config.User == "" {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("user: could not determine current user from environment."))
}
if errs != nil && len(errs.Errors) > 0 {
return errs
}
return nil
}
func (p *Provisioner) getVersion() error {
out, err := exec.Command(p.config.Command, "--version").Output()
if err != nil {
return fmt.Errorf(
"Error running \"%s --version\": %s", p.config.Command, err.Error())
}
versionRe := regexp.MustCompile(`\w (\d+\.\d+[.\d+]*)`)
matches := versionRe.FindStringSubmatch(string(out))
if matches == nil {
return fmt.Errorf(
"Could not find %s version in output:\n%s", p.config.Command, string(out))
}
version := matches[1]
log.Printf("%s version: %s", p.config.Command, version)
p.ansibleVersion = version
majVer, err := strconv.ParseUint(strings.Split(version, ".")[0], 10, 0)
if err != nil {
return fmt.Errorf("Could not parse major version from \"%s\".", version)
}
p.ansibleMajVersion = uint(majVer)
return nil
}
func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
ui.Say("Provisioning with Ansible...")
k, err := newUserKey(p.config.SSHAuthorizedKeyFile)
if err != nil {
return err
}
hostSigner, err := newSigner(p.config.SSHHostKeyFile)
// Remove the private key file
if len(k.privKeyFile) > 0 {
defer os.Remove(k.privKeyFile)
}
keyChecker := ssh.CertChecker{
UserKeyFallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
if user := conn.User(); user != p.config.User {
return nil, errors.New(fmt.Sprintf("authentication failed: %s is not a valid user", user))
}
if !bytes.Equal(k.Marshal(), pubKey.Marshal()) {
return nil, errors.New("authentication failed: unauthorized key")
}
return nil, nil
},
}
config := &ssh.ServerConfig{
AuthLogCallback: func(conn ssh.ConnMetadata, method string, err error) {
log.Printf("authentication attempt from %s to %s as %s using %s", conn.RemoteAddr(), conn.LocalAddr(), conn.User(), method)
},
PublicKeyCallback: keyChecker.Authenticate,
//NoClientAuth: true,
}
config.AddHostKey(hostSigner)
localListener, err := func() (net.Listener, error) {
port, err := strconv.ParseUint(p.config.LocalPort, 10, 16)
if err != nil {
return nil, err
}
tries := 1
if port != 0 {
tries = 10
}
for i := 0; i < tries; i++ {
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
port++
if err != nil {
ui.Say(err.Error())
continue
}
_, p.config.LocalPort, err = net.SplitHostPort(l.Addr().String())
if err != nil {
ui.Say(err.Error())
continue
}
return l, nil
}
return nil, errors.New("Error setting up SSH proxy connection")
}()
if err != nil {
return err
}
ui = newUi(ui)
p.adapter = newAdapter(p.done, localListener, config, p.config.SFTPCmd, ui, comm)
defer func() {
log.Print("shutting down the SSH proxy")
close(p.done)
p.adapter.Shutdown()
}()
go p.adapter.Serve()
if len(p.config.inventoryFile) == 0 {
tf, err := ioutil.TempFile(p.config.InventoryDirectory, "packer-provisioner-ansible")
if err != nil {
return fmt.Errorf("Error preparing inventory file: %s", err)
}
defer os.Remove(tf.Name())
host := fmt.Sprintf("%s ansible_host=127.0.0.1 ansible_user=%s ansible_port=%s\n",
p.config.HostAlias, p.config.User, p.config.LocalPort)
if p.ansibleMajVersion < 2 {
host = fmt.Sprintf("%s ansible_ssh_host=127.0.0.1 ansible_ssh_user=%s ansible_ssh_port=%s\n",
p.config.HostAlias, p.config.User, p.config.LocalPort)
}
w := bufio.NewWriter(tf)
w.WriteString(host)
for _, group := range p.config.Groups {
fmt.Fprintf(w, "[%s]\n%s", group, host)
}
for _, group := range p.config.EmptyGroups {
fmt.Fprintf(w, "[%s]\n", group)
}
if err := w.Flush(); err != nil {
tf.Close()
return fmt.Errorf("Error preparing inventory file: %s", err)
}
tf.Close()
p.config.inventoryFile = tf.Name()
defer func() {
p.config.inventoryFile = ""
}()
}
if err := p.executeAnsible(ui, comm, k.privKeyFile); err != nil {
return fmt.Errorf("Error executing Ansible: %s", err)
}
return nil
}
func (p *Provisioner) Cancel() {
if p.done != nil {
close(p.done)
}
if p.adapter != nil {
p.adapter.Shutdown()
}
os.Exit(0)
}
func (p *Provisioner) executeAnsible(ui packer.Ui, comm packer.Communicator, privKeyFile string) error {
playbook, _ := filepath.Abs(p.config.PlaybookFile)
inventory := p.config.inventoryFile
var envvars []string
args := []string{"--extra-vars", fmt.Sprintf("packer_build_name=%s packer_builder_type=%s",
p.config.PackerBuildName, p.config.PackerBuilderType),
"-i", inventory, playbook}
if len(privKeyFile) > 0 {
args = append(args, "--private-key", privKeyFile)
}
args = append(args, p.config.ExtraArguments...)
if len(p.config.AnsibleEnvVars) > 0 {
envvars = append(envvars, p.config.AnsibleEnvVars...)
}
cmd := exec.Command(p.config.Command, args...)
cmd.Env = os.Environ()
if len(envvars) > 0 {
cmd.Env = append(cmd.Env, envvars...)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
wg := sync.WaitGroup{}
repeat := func(r io.ReadCloser) {
reader := bufio.NewReader(r)
for {
line, err := reader.ReadString('\n')
if line != "" {
line = strings.TrimRightFunc(line, unicode.IsSpace)
ui.Message(line)
}
if err != nil {
if err == io.EOF {
break
} else {
ui.Error(err.Error())
break
}
}
}
wg.Done()
}
wg.Add(2)
go repeat(stdout)
go repeat(stderr)
ui.Say(fmt.Sprintf("Executing Ansible: %s", strings.Join(cmd.Args, " ")))
if err := cmd.Start(); err != nil {
return err
}
wg.Wait()
err = cmd.Wait()
if err != nil {
return fmt.Errorf("Non-zero exit status: %s", err)
}
return nil
}
func validateFileConfig(name string, config string, req bool) error {
if req {
if name == "" {
return fmt.Errorf("%s must be specified.", config)
}
}
info, err := os.Stat(name)
if err != nil {
return fmt.Errorf("%s: %s is invalid: %s", config, name, err)
} else if info.IsDir() {
return fmt.Errorf("%s: %s must point to a file", config, name)
}
return nil
}
func validateInventoryDirectoryConfig(name string) error {
info, err := os.Stat(name)
if err != nil {
return fmt.Errorf("inventory_directory: %s is invalid: %s", name, err)
} else if !info.IsDir() {
return fmt.Errorf("inventory_directory: %s must point to a directory", name)
}
return nil
}
type userKey struct {
ssh.PublicKey
privKeyFile string
}
func newUserKey(pubKeyFile string) (*userKey, error) {
userKey := new(userKey)
if len(pubKeyFile) > 0 {
pubKeyBytes, err := ioutil.ReadFile(pubKeyFile)
if err != nil {
return nil, errors.New("Failed to read public key")
}
userKey.PublicKey, _, _, _, err = ssh.ParseAuthorizedKey(pubKeyBytes)
if err != nil {
return nil, errors.New("Failed to parse authorized key")
}
return userKey, nil
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, errors.New("Failed to generate key pair")
}
userKey.PublicKey, err = ssh.NewPublicKey(key.Public())
if err != nil {
return nil, errors.New("Failed to extract public key from generated key pair")
}
// To support Ansible calling back to us we need to write
// this file down
privateKeyDer := x509.MarshalPKCS1PrivateKey(key)
privateKeyBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privateKeyDer,
}
tf, err := ioutil.TempFile("", "ansible-key")
if err != nil {
return nil, errors.New("failed to create temp file for generated key")
}
_, err = tf.Write(pem.EncodeToMemory(&privateKeyBlock))
if err != nil {
return nil, errors.New("failed to write private key to temp file")
}
err = tf.Close()
if err != nil {
return nil, errors.New("failed to close private key temp file")
}
userKey.privKeyFile = tf.Name()
return userKey, nil
}
type signer struct {
ssh.Signer
}
func newSigner(privKeyFile string) (*signer, error) {
signer := new(signer)
if len(privKeyFile) > 0 {
privateBytes, err := ioutil.ReadFile(privKeyFile)
if err != nil {
return nil, errors.New("Failed to load private host key")
}
signer.Signer, err = ssh.ParsePrivateKey(privateBytes)
if err != nil {
return nil, errors.New("Failed to parse private host key")
}
return signer, nil
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, errors.New("Failed to generate server key pair")
}
signer.Signer, err = ssh.NewSignerFromKey(key)
if err != nil {
return nil, errors.New("Failed to extract private key from generated key pair")
}
return signer, nil
}
// Ui provides concurrency-safe access to packer.Ui.
type Ui struct {
sem chan int
ui packer.Ui
}
func newUi(ui packer.Ui) packer.Ui {
return &Ui{sem: make(chan int, 1), ui: ui}
}
func (ui *Ui) Ask(s string) (string, error) {
ui.sem <- 1
ret, err := ui.ui.Ask(s)
<-ui.sem
return ret, err
}
func (ui *Ui) Say(s string) {
ui.sem <- 1
ui.ui.Say(s)
<-ui.sem
}
func (ui *Ui) Message(s string) {
ui.sem <- 1
ui.ui.Message(s)
<-ui.sem
}
func (ui *Ui) Error(s string) {
ui.sem <- 1
ui.ui.Error(s)
<-ui.sem
}
func (ui *Ui) Machine(t string, args ...string) {
ui.sem <- 1
ui.ui.Machine(t, args...)
<-ui.sem
}