/
datasource_secrets.go
97 lines (82 loc) · 2.26 KB
/
datasource_secrets.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
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/granular-oss/terraform-provider-credstash/credstash"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func dataSourceSecret() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceSecretRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "name of the secret",
},
"version": {
Type: schema.TypeInt,
Optional: true,
Description: "version of the secrets",
Default: 0,
},
"table": {
Type: schema.TypeString,
Optional: true,
Description: "name of DynamoDB table where the secrets are stored",
Default: "",
},
"context": {
Type: schema.TypeMap,
Optional: true,
Description: "encryption context for the secret",
},
"value": {
Type: schema.TypeString,
Computed: true,
Description: "value of the secret",
Sensitive: true,
},
},
}
}
func dataSourceSecretRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
// Warning or errors can be collected in a slice type
var diags diag.Diagnostics
client := meta.(*credstash.Client)
name := d.Get("name").(string)
version := d.Get("version").(int)
table := d.Get("table").(string)
context := credstash.NewEncryptionContextValue()
for k, v := range d.Get("context").(map[string]interface{}) {
stringValue := fmt.Sprintf("%v", v)
(*context)[k] = &stringValue
}
var value *credstash.DecryptedCredential
var err error
tflog.Debug(ctx, "dataSourceSecretRead getting secret", map[string]interface{}{
"name": name,
"version": version,
"table": table,
"context": context,
})
if version == 0 {
value, err = client.GetHighestVersionSecret(table, name, context)
} else {
value, err = client.GetSecret(name, table, client.PaddedInt(version), context)
}
if err != nil {
return diag.FromErr(err)
}
d.Set("value", value.Secret)
d.SetId(hash(value.Secret))
return diags
}
func hash(s string) string {
sha := sha256.Sum256([]byte(s))
return hex.EncodeToString(sha[:])
}