/
cluster_resource.go
221 lines (190 loc) · 6.19 KB
/
cluster_resource.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
package provider
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/k0sproject/k0sctl/cmd"
"os"
"strings"
"time"
)
const (
clusterResourceName = "cluster"
)
type clusterResource struct {
}
type clusterResourceModel struct {
Config string `tfsdk:"config"`
SSHPrivateKey string `tfsdk:"ssh_private_key"`
Kubeconfig types.String `tfsdk:"kubeconfig"`
}
func NewClusterResource() resource.Resource {
return &clusterResource{}
}
func (r *clusterResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_" + clusterResourceName
}
func (r *clusterResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"config": schema.StringAttribute{
Description: "k0sctl cluster configuration. Make sure to set host private key path to ./id_dsa",
Required: true,
},
"ssh_private_key": schema.StringAttribute{
Description: "SSH private key to authenticate with the hosts defined in configuration.",
Required: true,
Sensitive: true,
},
"kubeconfig": schema.StringAttribute{
Description: "The created k0s cluster admin kubeconfig",
Computed: true,
Sensitive: true,
},
},
}
}
func (r *clusterResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan clusterResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if diags.HasError() {
return
}
r.apply(ctx, &plan, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
// Save state
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *clusterResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state clusterResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if diags.HasError() {
return
}
if err := r.prepare(state.Config, state.SSHPrivateKey); err != nil {
resp.Diagnostics.AddError("Failed to create temporary files", err.Error())
return
}
defer func() {
if err := r.cleanUp(); err != nil {
resp.Diagnostics.AddWarning("Failed to clean up temporary files", err.Error())
}
}()
// Add 1 min timeout to k0sctl kubeconfig
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
kubeconfig, err := r.getKubeconfig(ctx)
if err != nil {
// If k0s cluster doesn't exist or DeadlineExceeded, clean resource state
if strings.Contains(err.Error(), "failed to read file /var/lib/k0s/kubelet.conf") || errors.Is(ctx.Err(), context.DeadlineExceeded) {
resp.State.RemoveResource(ctx)
} else {
resp.Diagnostics.AddError("Failed to read kubeconfig", err.Error())
}
return
}
state.Kubeconfig = types.StringValue(kubeconfig)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *clusterResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan clusterResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if diags.HasError() {
return
}
r.apply(ctx, &plan, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *clusterResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state clusterResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if diags.HasError() {
return
}
if err := r.prepare(state.Config, state.SSHPrivateKey); err != nil {
resp.Diagnostics.AddError("Failed to create temporary files", err.Error())
return
}
defer func() {
if err := r.cleanUp(); err != nil {
resp.Diagnostics.AddWarning("Failed to clean up temporary files", err.Error())
}
}()
// Run k0sctl reset
if err := cmd.App.Run([]string{"k0sctl", "reset", "--force"}); err != nil {
resp.Diagnostics.AddError("Failed to reset k0s cluster.", err.Error())
}
}
func (r *clusterResource) prepare(config, sshPrivateKey string) error {
// Save config file
if err := os.WriteFile("k0sctl.yaml", []byte(config), 0644); err != nil {
return fmt.Errorf("failed to write config to k0sctl.yaml: %v", err)
}
// Save SSH private key
if err := os.WriteFile("id_dsa", []byte(sshPrivateKey), 0644); err != nil {
return fmt.Errorf("failed to write config to id_dsa: %v", err)
}
return nil
}
func (r *clusterResource) cleanUp() error {
if err := os.Remove("k0sctl.yaml"); err != nil {
return fmt.Errorf("failed to remove k0sctl.yaml: %v", err)
}
if err := os.Remove("id_dsa"); err != nil {
return fmt.Errorf("failed to remove id_dsa: %v", err)
}
return nil
}
func (r *clusterResource) apply(ctx context.Context, model *clusterResourceModel, diagnostics *diag.Diagnostics) *clusterResourceModel {
if err := r.prepare(model.Config, model.SSHPrivateKey); err != nil {
diagnostics.AddError("Failed to create temporary files", err.Error())
return nil
}
defer func() {
// Remove local k0sctl.yaml and SSH private key
if err := r.cleanUp(); err != nil {
diagnostics.AddWarning("Failed to clean up temporary files", err.Error())
}
}()
// Run kubectl apply
if err := cmd.App.Run([]string{"k0sctl", "apply"}); err != nil {
diagnostics.AddError("failed to run k0sctl apply --kubeconfig-out kubeconfig", err.Error())
return nil
}
// Get kubeconfig
kubeconfig, err := r.getKubeconfig(ctx)
if err != nil {
diagnostics.AddError("Failed to get kubeconfig", err.Error())
return nil
}
model.Kubeconfig = types.StringValue(kubeconfig)
return model
}
func (r *clusterResource) getKubeconfig(ctx context.Context) (string, error) {
// Redirect app writer to buffer
buf := new(bytes.Buffer)
writer := cmd.App.Writer
cmd.App.Writer = buf
defer func() {
cmd.App.Writer = writer
}()
// Run k0sctl kubeconfig
if err := cmd.App.RunContext(ctx, []string{"k0sctl", "kubeconfig"}); err != nil {
return "", err
}
return buf.String(), nil
}