This repository has been archived by the owner on Dec 24, 2023. It is now read-only.
forked from hashicorp/terraform-provider-vault
/
resource_kubernetes_auth_backend_config.go
220 lines (180 loc) · 6.71 KB
/
resource_kubernetes_auth_backend_config.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
package vault
import (
"fmt"
"log"
"regexp"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/vault/api"
)
var (
kubernetesAuthBackendConfigFromPathRegex = regexp.MustCompile("^auth/(.+)/config$")
)
func kubernetesAuthBackendConfigResource() *schema.Resource {
return &schema.Resource{
Create: kubernetesAuthBackendConfigCreate,
Read: kubernetesAuthBackendConfigRead,
Update: kubernetesAuthBackendConfigUpdate,
Delete: kubernetesAuthBackendConfigDelete,
Exists: kubernetesAuthBackendConfigExists,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"kubernetes_host": {
Type: schema.TypeString,
Required: true,
Description: "Host must be a host string, a host:port pair, or a URL to the base of the Kubernetes API server.",
},
"kubernetes_ca_cert": {
Type: schema.TypeString,
Description: "PEM encoded CA cert for use by the TLS client used to talk with the Kubernetes API.",
Optional: true,
Default: "",
},
"token_reviewer_jwt": {
Type: schema.TypeString,
Description: "A service account JWT used to access the TokenReview API to validate other JWTs during login. If not set the JWT used for login will be used to access the API.",
Default: "",
Optional: true,
Sensitive: true,
},
"pem_keys": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Description: "Optional list of PEM-formatted public keys or certificates used to verify the signatures of Kubernetes service account JWTs. If a certificate is given, its public key will be extracted. Not every installation of Kubernetes exposes these keys.",
Optional: true,
},
"backend": {
Type: schema.TypeString,
Optional: true,
Description: "Unique name of the kubernetes backend to configure.",
ForceNew: true,
Default: "kubernetes",
// standardise on no beginning or trailing slashes
StateFunc: func(v interface{}) string {
return strings.Trim(v.(string), "/")
},
},
},
}
}
func kubernetesAuthBackendConfigPath(backend string) string {
return "auth/" + strings.Trim(backend, "/") + "/config"
}
func kubernetesAuthBackendConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*api.Client)
backend := d.Get("backend").(string)
path := kubernetesAuthBackendConfigPath(backend)
log.Printf("[DEBUG] Writing Kubernetes auth backend config %q", path)
data := map[string]interface{}{}
if v, ok := d.GetOk("kubernetes_ca_cert"); ok {
data["kubernetes_ca_cert"] = v.(string)
}
if v, ok := d.GetOk("token_reviewer_jwt"); ok {
data["token_reviewer_jwt"] = v.(string)
}
if v, ok := d.GetOkExists("pem_keys"); ok {
var pemKeys []string
for _, pemKey := range v.([]interface{}) {
pemKeys = append(pemKeys, pemKey.(string))
}
data["pem_keys"] = strings.Join(pemKeys, ",")
}
data["kubernetes_host"] = d.Get("kubernetes_host").(string)
_, err := client.Logical().Write(path, data)
if err != nil {
return fmt.Errorf("error writing Kubernetes auth backend config %q: %s", path, err)
}
d.SetId(path)
// NOTE: Since reading the auth/<backend>/config does
// not return the `token_reviewer_jwt`,
// set it from data after successfully storing it in Vault.
d.Set("token_reviewer_jwt", data["token_reviewer_jwt"])
log.Printf("[DEBUG] Wrote Kubernetes auth backend config %q", path)
return kubernetesAuthBackendConfigRead(d, meta)
}
func kubernetesAuthBackendConfigBackendFromPath(path string) (string, error) {
if !kubernetesAuthBackendConfigFromPathRegex.MatchString(path) {
return "", fmt.Errorf("no backend found")
}
res := kubernetesAuthBackendConfigFromPathRegex.FindStringSubmatch(path)
if len(res) != 2 {
return "", fmt.Errorf("unexpected number of matches (%d) for backend", len(res))
}
return res[1], nil
}
func kubernetesAuthBackendConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*api.Client)
path := d.Id()
backend, err := kubernetesAuthBackendConfigBackendFromPath(path)
if err != nil {
return fmt.Errorf("invalid path %q for Kubernetes auth backend config: %s", path, err)
}
log.Printf("[DEBUG] Reading Kubernetes auth backend config %q", path)
resp, err := client.Logical().Read(path)
if err != nil {
return fmt.Errorf("error reading Kubernetes auth backend config %q: %s", path, err)
}
log.Printf("[DEBUG] Read Kubernetes auth backend config %q", path)
if resp == nil {
log.Printf("[WARN] Kubernetes auth backend config %q not found, removing from state", path)
d.SetId("")
return nil
}
d.Set("backend", backend)
d.Set("kubernetes_host", resp.Data["kubernetes_host"])
d.Set("kubernetes_ca_cert", resp.Data["kubernetes_ca_cert"])
iPemKeys := resp.Data["pem_keys"].([]interface{})
pemKeys := make([]string, 0, len(iPemKeys))
for _, iPemKey := range iPemKeys {
pemKeys = append(pemKeys, iPemKey.(string))
}
d.Set("pem_keys", pemKeys)
return nil
}
func kubernetesAuthBackendConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*api.Client)
path := d.Id()
log.Printf("[DEBUG] Updating Kubernetes auth backend config %q", path)
data := map[string]interface{}{}
if v, ok := d.GetOk("kubernetes_ca_cert"); ok {
data["kubernetes_ca_cert"] = v.(string)
}
if v, ok := d.GetOk("token_reviewer_jwt"); ok {
data["token_reviewer_jwt"] = v.(string)
}
if v, ok := d.GetOkExists("pem_keys"); ok {
var pemKeys []string
for _, pemKey := range v.([]interface{}) {
pemKeys = append(pemKeys, pemKey.(string))
}
data["pem_keys"] = strings.Join(pemKeys, ",")
}
data["kubernetes_host"] = d.Get("kubernetes_host").(string)
_, err := client.Logical().Write(path, data)
if err != nil {
return fmt.Errorf("error updating Kubernetes auth backend config %q: %s", path, err)
}
// NOTE: Only `SetId` after it's successfully written in Vault
d.SetId(path)
log.Printf("[DEBUG] Updated Kubernetes auth backend config %q", path)
return kubernetesAuthBackendConfigRead(d, meta)
}
func kubernetesAuthBackendConfigDelete(d *schema.ResourceData, meta interface{}) error {
path := d.Id()
log.Printf("[DEBUG] Deleted Kubernetes auth backend config %q", path)
d.SetId("")
return nil
}
func kubernetesAuthBackendConfigExists(d *schema.ResourceData, meta interface{}) (bool, error) {
client := meta.(*api.Client)
path := d.Id()
log.Printf("[DEBUG] Checking if Kubernetes auth backend config %q exists", path)
resp, err := client.Logical().Read(path)
if err != nil {
return true, fmt.Errorf("error checking if Kubernetes auth backend config %q exists: %s", path, err)
}
log.Printf("[DEBUG] Checked if Kubernetes auth backend config %q exists", path)
return resp != nil, nil
}