-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
resource_provisioner.go
346 lines (298 loc) · 8.48 KB
/
resource_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
package puppet
import (
"bytes"
"context"
"fmt"
"io"
"strings"
"time"
"github.com/hashicorp/terraform/builtin/provisioners/puppet/bolt"
"github.com/hashicorp/terraform/communicator"
"github.com/hashicorp/terraform/communicator/remote"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/go-linereader"
"gopkg.in/yaml.v2"
)
type provisioner struct {
Server string
ServerUser string
OSType string
Certname string
Environment string
Autosign bool
OpenSource bool
UseSudo bool
BoltTimeout time.Duration
CustomAttributes map[string]interface{}
ExtensionRequests map[string]interface{}
runPuppetAgent func() error
installPuppetAgent func() error
uploadFile func(f io.Reader, dir string, filename string) error
defaultCertname func() (string, error)
instanceState *terraform.InstanceState
output terraform.UIOutput
comm communicator.Communicator
}
type csrAttributes struct {
CustomAttributes map[string]string `yaml:"custom_attributes"`
ExtensionRequests map[string]string `yaml:"extension_requests"`
}
// Provisioner returns a Puppet resource provisioner.
func Provisioner() terraform.ResourceProvisioner {
return &schema.Provisioner{
Schema: map[string]*schema.Schema{
"server": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"server_user": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "root",
},
"os_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"linux", "windows"}, false),
},
"use_sudo": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"autosign": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"open_source": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"certname": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"extension_requests": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
},
"custom_attributes": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
},
"environment": &schema.Schema{
Type: schema.TypeString,
Default: "production",
Optional: true,
},
"bolt_timeout": &schema.Schema{
Type: schema.TypeString,
Default: "5m",
Optional: true,
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
_, err := time.ParseDuration(val.(string))
if err != nil {
errs = append(errs, err)
}
return warns, errs
},
},
},
ApplyFunc: applyFn,
}
}
func applyFn(ctx context.Context) error {
output := ctx.Value(schema.ProvOutputKey).(terraform.UIOutput)
state := ctx.Value(schema.ProvRawStateKey).(*terraform.InstanceState)
configData := ctx.Value(schema.ProvConfigDataKey).(*schema.ResourceData)
p, err := decodeConfig(configData)
if err != nil {
return err
}
p.instanceState = state
p.output = output
if p.OSType == "" {
switch connType := state.Ephemeral.ConnInfo["type"]; connType {
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", connType)
}
}
switch p.OSType {
case "linux":
p.runPuppetAgent = p.linuxRunPuppetAgent
p.installPuppetAgent = p.linuxInstallPuppetAgent
p.uploadFile = p.linuxUploadFile
p.defaultCertname = p.linuxDefaultCertname
case "windows":
p.runPuppetAgent = p.windowsRunPuppetAgent
p.installPuppetAgent = p.windowsInstallPuppetAgent
p.uploadFile = p.windowsUploadFile
p.UseSudo = false
p.defaultCertname = p.windowsDefaultCertname
default:
return fmt.Errorf("Unsupported OS type: %s", p.OSType)
}
comm, err := communicator.New(state)
if err != nil {
return err
}
retryCtx, cancel := context.WithTimeout(ctx, comm.Timeout())
defer cancel()
err = communicator.Retry(retryCtx, func() error {
return comm.Connect(output)
})
if err != nil {
return err
}
defer comm.Disconnect()
p.comm = comm
if p.OpenSource {
p.installPuppetAgent = p.installPuppetAgentOpenSource
}
csrAttrs := new(csrAttributes)
csrAttrs.CustomAttributes = make(map[string]string)
for k, v := range p.CustomAttributes {
csrAttrs.CustomAttributes[k] = v.(string)
}
csrAttrs.ExtensionRequests = make(map[string]string)
for k, v := range p.ExtensionRequests {
csrAttrs.ExtensionRequests[k] = v.(string)
}
if p.Autosign {
if p.Certname == "" {
p.Certname, _ = p.defaultCertname()
}
autosignToken, err := p.generateAutosignToken(p.Certname)
if err != nil {
return fmt.Errorf("Failed to generate an autosign token: %s", err)
}
csrAttrs.CustomAttributes["challengePassword"] = autosignToken
}
if err = p.writeCSRAttributes(csrAttrs); err != nil {
return fmt.Errorf("Failed to write csr_attributes.yaml: %s", err)
}
if err = p.installPuppetAgent(); err != nil {
return err
}
if err = p.runPuppetAgent(); err != nil {
return err
}
return nil
}
func (p *provisioner) writeCSRAttributes(attrs *csrAttributes) (rerr error) {
content, err := yaml.Marshal(attrs)
if err != nil {
return fmt.Errorf("Failed to marshal CSR attributes to YAML: %s", err)
}
configDir := map[string]string{
"linux": "/etc/puppetlabs/puppet",
"windows": "C:\\ProgramData\\PuppetLabs\\Puppet\\etc",
}
return p.uploadFile(bytes.NewBuffer(content), configDir[p.OSType], "csr_attributes.yaml")
}
func (p *provisioner) generateAutosignToken(certname string) (string, error) {
task := "autosign::generate_token"
masterConnInfo := map[string]string{
"type": "ssh",
"host": p.Server,
"user": p.ServerUser,
}
result, err := bolt.Task(
masterConnInfo,
p.BoltTimeout,
p.ServerUser != "root",
task,
map[string]string{"certname": certname},
)
if err != nil {
return "", err
}
if result.Items[0].Status != "success" {
return "", fmt.Errorf("Bolt %s failed on %s: %v",
task,
result.Items[0].Node,
result.Items[0].Result["_error"],
)
}
return result.Items[0].Result["_output"], nil
}
func (p *provisioner) installPuppetAgentOpenSource() error {
task := "puppet_agent::install"
connType := p.instanceState.Ephemeral.ConnInfo["type"]
if connType == "" {
connType = "ssh"
}
agentConnInfo := map[string]string{
"type": connType,
"host": p.instanceState.Ephemeral.ConnInfo["host"],
"user": p.instanceState.Ephemeral.ConnInfo["user"],
"password": p.instanceState.Ephemeral.ConnInfo["password"], // Required on Windows only
}
result, err := bolt.Task(
agentConnInfo,
p.BoltTimeout,
p.UseSudo,
task,
nil,
)
if err != nil || result.Items[0].Status != "success" {
return fmt.Errorf("%s failed: %s\n%+v", task, err, result)
}
return nil
}
func (p *provisioner) runCommand(command string) (stdout string, err error) {
if p.UseSudo {
command = "sudo " + command
}
var stdoutBuffer bytes.Buffer
outR, outW := io.Pipe()
errR, errW := io.Pipe()
outTee := io.TeeReader(outR, &stdoutBuffer)
go p.copyToOutput(outTee)
go p.copyToOutput(errR)
defer outW.Close()
defer errW.Close()
cmd := &remote.Cmd{
Command: command,
Stdout: outW,
Stderr: errW,
}
err = p.comm.Start(cmd)
if err != nil {
err = fmt.Errorf("Error executing command %q: %v", cmd.Command, err)
return stdout, err
}
err = cmd.Wait()
stdout = strings.TrimSpace(stdoutBuffer.String())
return stdout, err
}
func (p *provisioner) copyToOutput(reader io.Reader) {
lr := linereader.New(reader)
for line := range lr.Ch {
p.output.Output(line)
}
}
func decodeConfig(d *schema.ResourceData) (*provisioner, error) {
p := &provisioner{
UseSudo: d.Get("use_sudo").(bool),
Server: d.Get("server").(string),
ServerUser: d.Get("server_user").(string),
OSType: strings.ToLower(d.Get("os_type").(string)),
Autosign: d.Get("autosign").(bool),
OpenSource: d.Get("open_source").(bool),
Certname: strings.ToLower(d.Get("certname").(string)),
ExtensionRequests: d.Get("extension_requests").(map[string]interface{}),
CustomAttributes: d.Get("custom_attributes").(map[string]interface{}),
Environment: d.Get("environment").(string),
}
p.BoltTimeout, _ = time.ParseDuration(d.Get("bolt_timeout").(string))
return p, nil
}