This repository has been archived by the owner on Jun 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provisioner.go
178 lines (151 loc) · 4.25 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
package main
import (
"context"
"errors"
"fmt"
"strings"
"time"
salt "github.com/finarfin/go-salt-netapi-client/cherrypy"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
// ErrorHighstateFailed indicates that highstate command failed on the minion
var ErrorHighstateFailed = errors.New("Highstate execution failed")
// ErrorMinionNotAvailable indicates that the minion was avaliable (offline or not registered)
var ErrorMinionNotAvailable = errors.New("Minion is not available")
/*
Provisioner is waits for a minion to connect to a master;
and applies highstate then reports whether it completed successfully.
*/
func Provisioner() terraform.ResourceProvisioner {
return &schema.Provisioner{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Required: true,
},
"username": {
Type: schema.TypeString,
Required: true,
},
"password": {
Type: schema.TypeString,
Required: true,
},
"backend": {
Type: schema.TypeString,
Required: true,
},
"skip_verify": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"minion_id": {
Type: schema.TypeString,
Required: true,
},
"timeout_minutes": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
},
"interval_secs": {
Type: schema.TypeInt,
Optional: true,
Default: 10,
},
},
ApplyFunc: apply,
}
}
func apply(ctx context.Context) error {
o := ctx.Value(schema.ProvOutputKey).(terraform.UIOutput)
d := ctx.Value(schema.ProvConfigDataKey).(*schema.ResourceData)
cli := salt.NewClient(
d.Get("address").(string),
d.Get("username").(string),
d.Get("password").(string),
d.Get("backend").(string),
d.Get("skip_verify").(bool),
)
if err := cli.Login(ctx); err != nil {
return err
}
timeout := time.Duration(d.Get("timeout_minutes").(int)) * time.Minute
interval := time.Duration(d.Get("interval_secs").(int)) * time.Second
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
minion := d.Get("minion_id").(string)
attempts := 0
maxAttempts := 3
for {
if attempts >= maxAttempts {
return fmt.Errorf("%w: could not execute highstate in %d attempts", ErrorMinionNotAvailable, attempts)
}
attempts++
o.Output(fmt.Sprintf("Waiting for minion %s to register with master", minion))
if err := waitForMinion(ctx, o, cli, minion, interval, timeout); err != nil {
return err
}
o.Output(fmt.Sprintf("Executing state.highstate on minion %s", minion))
res, err := cli.RunCommand(ctx, salt.Command{
Client: salt.LocalClient,
Target: salt.ListTarget{Targets: []string{minion}},
Function: "state.highstate",
})
if err != nil {
return err
}
rd, ok := res.(map[string]interface{})
if !ok {
return fmt.Errorf("invalid response from Salt Master: expected map; received %s", res)
}
md, ok := rd[minion]
if !ok {
o.Output(fmt.Sprintf("Minion %s is not registered. Will retry.", minion))
continue
}
data, ok := md.(map[string]interface{})
if !ok {
if _, ok := md.(bool); ok {
o.Output(fmt.Sprintf("Minion %s is not available. Will retry.", minion))
continue
}
return fmt.Errorf("invalid highstate response: expected map; received: %s", data)
}
if data["retcode"].(float64) != 0 {
ls, ok := data["ret"].(map[string]interface{})
if ok {
var fails []string
for k, v := range ls {
state := v.(map[string]interface{})
if !state["result"].(bool) {
fails = append(fails, fmt.Sprintf("State %s failed on %s: %s", k, minion, state["comment"]))
}
}
return fmt.Errorf("%w:\n%s", ErrorHighstateFailed, strings.Join(fails, "\n"))
}
return fmt.Errorf("Highstate execution failed on %s: %s", minion, data["ret"])
}
return nil
}
}
func waitForMinion(ctx context.Context, o terraform.UIOutput, cli *salt.Client, minion string, interval time.Duration, timeout time.Duration) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
minionData, err := cli.Minion(ctx, minion)
if err != nil && !errors.Is(err, salt.ErrorMinionNotFound) {
return err
} else if minionData == nil || minionData.Grains == nil {
time.Sleep(interval)
continue
}
}
break
}
return nil
}