generated from hashicorp/terraform-provider-scaffolding
-
Notifications
You must be signed in to change notification settings - Fork 43
/
resource_consul_cluster_root_token.go
260 lines (222 loc) · 8.02 KB
/
resource_consul_cluster_root_token.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package providersdkv2
import (
"context"
"encoding/base64"
"fmt"
"log"
"path/filepath"
"strings"
"time"
"github.com/hashicorp/hcp-sdk-go/clients/cloud-shared/v1/models"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-hcp/internal/clients"
)
// defaultRootTokenTimeoutDuration is the amount of time that can elapse
// before a cluster read operation should timeout.
var defaultRootTokenTimeoutDuration = time.Minute * 5
// rootTokenKubernetesSecretTemplate is the template used to generate a
// kubernetes formatted secret for the cluster root token.
const rootTokenKubernetesSecretTemplate = `apiVersion: v1
kind: Secret
metadata:
name: %s-bootstrap-token
type: Opaque
data:
token: %s`
// resourceConsulClusterRootToken represents an HCP Consul cluster.
func resourceConsulClusterRootToken() *schema.Resource {
return &schema.Resource{
Description: "The cluster root token resource is the token used to bootstrap the cluster's ACL system. " +
"You can also generate this root token from the HCP Consul UI.",
CreateContext: resourceConsulClusterRootTokenCreate,
ReadContext: resourceConsulClusterRootTokenRead,
DeleteContext: resourceConsulClusterRootTokenDelete,
Timeouts: &schema.ResourceTimeout{
Default: &defaultRootTokenTimeoutDuration,
},
Schema: map[string]*schema.Schema{
// required inputs
"cluster_id": {
Description: "The ID of the HCP Consul cluster.",
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: validateSlugIDOrID,
},
// Optional inputs
"project_id": {
Description: `
The ID of the HCP project where the HCP Consul cluster is located.
If not specified, the project specified in the HCP Provider config block will be used, if configured.
If a project is not configured in the HCP Provider config block, the oldest project in the organization will be used.`,
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IsUUID,
Computed: true,
},
// Computed outputs
"accessor_id": {
Description: "The accessor ID of the root ACL token.",
Type: schema.TypeString,
Computed: true,
},
"secret_id": {
Description: "The secret ID of the root ACL token.",
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"kubernetes_secret": {
Description: "The root ACL token Base64 encoded in a Kubernetes secret.",
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
},
}
}
// resourceClusterRootTokenCreate will generate a new root token for the cluster
func resourceConsulClusterRootTokenCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*clients.Client)
clusterID := d.Get("cluster_id").(string)
if matchesID(clusterID) {
clusterID = filepath.Base(clusterID)
}
projectID, err := GetProjectID(d.Get("project_id").(string), client.Config.ProjectID)
if err != nil {
return diag.Errorf("unable to retrieve project ID: %v", err)
}
loc := &models.HashicorpCloudLocationLocation{
OrganizationID: client.Config.OrganizationID,
ProjectID: projectID,
}
log.Printf("[INFO] reading Consul cluster (%s) [project_id=%s, organization_id=%s]", clusterID, loc.ProjectID, loc.OrganizationID)
_, err = clients.GetConsulClusterByID(ctx, client, loc, clusterID)
if err != nil {
if clients.IsResponseCodeNotFound(err) {
return diag.Errorf("unable to create root ACL token; Consul cluster (%s) not found",
clusterID,
)
}
return diag.Errorf("unable to check for presence of an existing Consul cluster (%s): %v",
clusterID,
err,
)
}
rootTokenResp, err := clients.CreateCustomerRootACLToken(ctx, client, loc, clusterID)
if err != nil {
return diag.Errorf("error creating HCP Consul cluster root ACL token (cluster_id %q) (project_id %q): %+v",
clusterID,
projectID,
err,
)
}
// Set root token resource data here since 'read' is a no-op
err = d.Set("accessor_id", rootTokenResp.ACLToken.AccessorID)
if err != nil {
return diag.FromErr(err)
}
secretID := rootTokenResp.ACLToken.SecretID
err = d.Set("secret_id", secretID)
if err != nil {
return diag.FromErr(err)
}
err = d.Set("kubernetes_secret", generateKubernetesSecret(secretID, clusterID))
if err != nil {
return diag.FromErr(err)
}
d.SetId(rootTokenResp.ACLToken.AccessorID)
return nil
}
// resourceConsulClusterRootTokenRead will act as a no-op as the root token is not persisted in
// any way that it can be fetched and read
func resourceConsulClusterRootTokenRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*clients.Client)
clusterID := d.Get("cluster_id").(string)
if matchesID(clusterID) {
clusterID = filepath.Base(clusterID)
}
projectID, err := GetProjectID(d.Get("project_id").(string), client.Config.ProjectID)
if err != nil {
return diag.Errorf("unable to retrieve project ID: %v", err)
}
loc := &models.HashicorpCloudLocationLocation{
OrganizationID: client.Config.OrganizationID,
ProjectID: projectID,
}
log.Printf("[INFO] reading Consul cluster (%s) [project_id=%s, organization_id=%s]", clusterID, loc.ProjectID, loc.OrganizationID)
_, err = clients.GetConsulClusterByID(ctx, client, loc, clusterID)
if err != nil {
if clients.IsResponseCodeNotFound(err) {
// No cluster exists, so this root token should be removed from state
log.Printf("[WARN] no HCP Consul cluster found with (cluster_id %q) (project_id %q); removing root token.",
clusterID,
projectID,
)
d.SetId("")
return nil
}
return diag.Errorf("unable to check for presence of an existing Consul cluster (cluster_id %q) (project_id %q): %v",
clusterID,
projectID,
err,
)
}
return nil
}
// resourceClusterRootTokenDelete will "delete" an existing token by creating a new one,
// that will not be returned, and invalidating the previous token for the cluster.
func resourceConsulClusterRootTokenDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*clients.Client)
clusterID := d.Get("cluster_id").(string)
if matchesID(clusterID) {
clusterID = filepath.Base(clusterID)
}
projectID, err := GetProjectID(d.Get("project_id").(string), client.Config.ProjectID)
if err != nil {
return diag.Errorf("unable to retrieve project ID: %v", err)
}
loc := &models.HashicorpCloudLocationLocation{
OrganizationID: client.Config.OrganizationID,
ProjectID: projectID,
}
log.Printf("[INFO] reading Consul cluster (%s) [project_id=%s, organization_id=%s]", clusterID, loc.ProjectID, loc.OrganizationID)
_, err = clients.GetConsulClusterByID(ctx, client, loc, clusterID)
if err != nil {
if clients.IsResponseCodeNotFound(err) {
// No cluster exists, so this root token should be removed from state
log.Printf("[WARN] no HCP Consul cluster found with (cluster_id %q) (project_id %q); removing root token.",
clusterID,
projectID,
)
return nil
}
return diag.Errorf("unable to check for presence of an existing Consul cluster (%s): %v",
clusterID,
err,
)
}
// generate a new token to invalidate the previous one, but discard the response
_, err = clients.CreateCustomerRootACLToken(ctx, client, loc, clusterID)
if err != nil {
return diag.Errorf("unable to delete Consul cluster (%s) root ACL token: %v",
clusterID,
err,
)
}
return nil
}
// generateKubernetesSecret will generate a Kubernetes secret with
// a base64 encoded root token secret as it's token.
func generateKubernetesSecret(rootTokenSecretID, clusterID string) string {
return fmt.Sprintf(rootTokenKubernetesSecretTemplate,
// lowercase the name
strings.ToLower(clusterID),
// base64 encode the secret value
base64.StdEncoding.EncodeToString([]byte(rootTokenSecretID)))
}