/
client_ca_cert_resource.go
274 lines (237 loc) · 9.17 KB
/
client_ca_cert_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
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
/*
Copyright 2023 The Cockroach Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package provider
import (
"context"
"fmt"
"net/http"
"time"
"github.com/cockroachdb/cockroach-cloud-sdk-go/pkg/client"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
)
const (
clientCACertEndpointTimeout = time.Minute * 10
)
type clientCACertResource struct {
provider *provider
}
func NewClientCACertResource() resource.Resource {
return &clientCACertResource{}
}
func (r *clientCACertResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages client CA certs.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Required: true,
MarkdownDescription: "Cluster ID.",
},
"x509_pem_cert": schema.StringAttribute{
Required: true,
MarkdownDescription: "X509 certificate in PEM format.",
},
"status": schema.StringAttribute{
MarkdownDescription: "Status of client CA certs on a cluster.",
Computed: true,
},
},
}
}
func (r *clientCACertResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_client_ca_cert"
}
func (r *clientCACertResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
var ok bool
if r.provider, ok = req.ProviderData.(*provider); !ok {
resp.Diagnostics.AddError("Internal provider error",
fmt.Sprintf("Error in Configure: expected %T but got %T", provider{}, req.ProviderData))
}
}
func (r *clientCACertResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
if r.provider == nil || !r.provider.configured {
addConfigureProviderErr(&resp.Diagnostics)
return
}
// Retrieve values from plan
var plan ClientCACertResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Ensure cluster is DEDICATED
cluster, _, err := r.provider.service.GetCluster(ctx, plan.ID.ValueString())
if err != nil {
resp.Diagnostics.AddError("Error getting cluster info", formatAPIErrorMessage(err))
return
}
if cluster.Config.Serverless != nil {
resp.Diagnostics.AddError(
"Incompatible cluster type",
"Client CA Cert management is only available for dedicated clusters",
)
return
}
// Generate API request from plan
setClientCACertReq := client.NewSetClientCACertRequest(plan.X509PemCert.ValueString())
certInfo, _, err := r.provider.service.SetClientCACert(ctx, plan.ID.ValueString(), setClientCACertReq)
if err != nil {
resp.Diagnostics.AddError("Error updating Client CA Cert", formatAPIErrorMessage(err))
return
}
// poll until update completes
err = retry.RetryContext(ctx, clientCACertEndpointTimeout,
waitForClientCACertReady(ctx, plan.ID.ValueString(), r.provider.service, certInfo))
if err != nil {
resp.Diagnostics.AddError("Client CA Cert update timed out and may have failed", formatAPIErrorMessage(err))
return
}
var state ClientCACertResourceModel
clientCACertInfoToTerraformState(certInfo, plan.ID.ValueString(), &state)
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
}
func (r *clientCACertResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
if r.provider == nil || !r.provider.configured {
addConfigureProviderErr(&resp.Diagnostics)
return
}
var state ClientCACertResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
clusterId := state.ID.ValueString()
certInfo, httpResp, err := r.provider.service.GetClientCACert(ctx, clusterId)
if err != nil {
if httpResp != nil && httpResp.StatusCode == http.StatusNotFound {
resp.Diagnostics.AddWarning(fmt.Sprintf("Cluster '%s' was not found", clusterId), "Removing from state.")
resp.State.RemoveResource(ctx)
} else {
resp.Diagnostics.AddError("Error getting Client CA Cert info", formatAPIErrorMessage(err))
}
return
}
clientCACertInfoToTerraformState(certInfo, clusterId, &state)
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
}
func (r *clientCACertResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
// Get plan values
var plan ClientCACertResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Get current state
var state ClientCACertResourceModel
diags = req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only update cert if non-null.
// Setting it to null will essentially cause TF to forget the field.
if !IsKnown(plan.X509PemCert) {
if IsKnown(state.X509PemCert) {
resp.Diagnostics.AddWarning(
"Client CA Cert will not be changed",
"Setting the cert field to null will not clear the cert, it will only remove it from Terraform state. Delete the resource to unset a cert.",
)
}
} else {
newCert := plan.X509PemCert.ValueString()
updateReq := client.UpdateClientCACertRequest{X509PemCert: &newCert}
certInfo, _, err := r.provider.service.UpdateClientCACert(ctx, plan.ID.ValueString(), &updateReq)
if err != nil {
resp.Diagnostics.AddError("Error updating Client CA Cert", formatAPIErrorMessage(err))
return
}
// poll until update completes
err = retry.RetryContext(ctx, clientCACertEndpointTimeout,
waitForClientCACertReady(ctx, plan.ID.ValueString(), r.provider.service, certInfo))
if err != nil {
resp.Diagnostics.AddError("Client CA Cert update timed out and may have failed", formatAPIErrorMessage(err))
return
}
clientCACertInfoToTerraformState(certInfo, plan.ID.ValueString(), &state)
}
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
}
func (r *clientCACertResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state ClientCACertResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
certInfo, httpResp, err := r.provider.service.DeleteClientCACert(ctx, state.ID.ValueString())
if err != nil {
if httpResp != nil && httpResp.StatusCode == http.StatusNotFound {
// Already deleted, ignore error
} else {
resp.Diagnostics.AddError("Error deleting Client CA Cert", formatAPIErrorMessage(err))
return
}
}
// poll until update completes
err = retry.RetryContext(ctx, clientCACertEndpointTimeout,
waitForClientCACertReady(ctx, state.ID.ValueString(), r.provider.service, certInfo))
if err != nil {
resp.Diagnostics.AddError("Client CA Cert update timed out and may have failed", formatAPIErrorMessage(err))
return
}
// TF will automatically remove the resource from state if there are no error diags.
// https://developer.hashicorp.com/terraform/plugin/framework/resources/delete#recommendations
}
func (r *clientCACertResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
func waitForClientCACertReady(
ctx context.Context, clusterId string, cl client.Service, certInfo *client.ClientCACertInfo,
) retry.RetryFunc {
return func() *retry.RetryError {
res, httpResp, err := cl.GetClientCACert(ctx, clusterId)
if err != nil {
if httpResp != nil && httpResp.StatusCode < http.StatusInternalServerError {
return retry.NonRetryableError(fmt.Errorf("error getting client ca cert: %s", formatAPIErrorMessage(err)))
} else {
return retry.RetryableError(fmt.Errorf("encountered a server error while reading client ca cert status - trying again"))
}
}
*certInfo = *res
switch status := certInfo.GetStatus(); status {
case client.CLIENTCACERTSTATUS_PENDING:
return retry.RetryableError(fmt.Errorf("client ca cert update is still pending"))
case client.CLIENTCACERTSTATUS_FAILED:
return retry.NonRetryableError(fmt.Errorf("client ca cert update failed"))
default:
return nil
}
}
}
func clientCACertInfoToTerraformState(certInfo *client.ClientCACertInfo, clusterId string, state *ClientCACertResourceModel) {
state.ID = types.StringValue(clusterId) // not pulled from cert info since not available
state.X509PemCert = types.StringValue(certInfo.GetX509PemCert())
state.Status = types.StringValue(string(certInfo.GetStatus()))
}