forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_id.go
103 lines (82 loc) · 1.99 KB
/
resource_id.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
package random
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"math/big"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceId() *schema.Resource {
return &schema.Resource{
Create: CreateID,
Read: RepopulateEncodings,
Delete: schema.RemoveFromState,
Schema: map[string]*schema.Schema{
"keepers": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"byte_length": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"b64": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Use b64_url for old behavior, or b64_std for standard base64 encoding",
},
"b64_url": {
Type: schema.TypeString,
Computed: true,
},
"b64_std": {
Type: schema.TypeString,
Computed: true,
},
"hex": {
Type: schema.TypeString,
Computed: true,
},
"dec": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func CreateID(d *schema.ResourceData, meta interface{}) error {
byteLength := d.Get("byte_length").(int)
bytes := make([]byte, byteLength)
n, err := rand.Reader.Read(bytes)
if n != byteLength {
return errors.New("generated insufficient random bytes")
}
if err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
}
b64Str := base64.RawURLEncoding.EncodeToString(bytes)
d.SetId(b64Str)
return RepopulateEncodings(d, meta)
}
func RepopulateEncodings(d *schema.ResourceData, _ interface{}) error {
base64Str := d.Id()
bytes, err := base64.RawURLEncoding.DecodeString(base64Str)
if err != nil {
return errwrap.Wrapf("Error decoding ID: {{err}}", err)
}
b64StdStr := base64.StdEncoding.EncodeToString(bytes)
hexStr := hex.EncodeToString(bytes)
bigInt := big.Int{}
bigInt.SetBytes(bytes)
decStr := bigInt.String()
d.Set("b64", base64Str)
d.Set("b64_url", base64Str)
d.Set("b64_std", b64StdStr)
d.Set("hex", hexStr)
d.Set("dec", decStr)
return nil
}