github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/random/resource_id.go (about) 1 package random 2 3 import ( 4 "crypto/rand" 5 "encoding/base64" 6 "encoding/hex" 7 "errors" 8 "math/big" 9 10 "github.com/hashicorp/errwrap" 11 "github.com/hashicorp/terraform/helper/schema" 12 ) 13 14 func resourceId() *schema.Resource { 15 return &schema.Resource{ 16 Create: CreateID, 17 Read: RepopulateEncodings, 18 Delete: schema.RemoveFromState, 19 20 Schema: map[string]*schema.Schema{ 21 "keepers": { 22 Type: schema.TypeMap, 23 Optional: true, 24 ForceNew: true, 25 }, 26 27 "byte_length": { 28 Type: schema.TypeInt, 29 Required: true, 30 ForceNew: true, 31 }, 32 33 "prefix": { 34 Type: schema.TypeString, 35 Optional: true, 36 ForceNew: true, 37 }, 38 39 "b64": { 40 Type: schema.TypeString, 41 Computed: true, 42 Deprecated: "Use b64_url for old behavior, or b64_std for standard base64 encoding", 43 }, 44 45 "b64_url": { 46 Type: schema.TypeString, 47 Computed: true, 48 }, 49 50 "b64_std": { 51 Type: schema.TypeString, 52 Computed: true, 53 }, 54 55 "hex": { 56 Type: schema.TypeString, 57 Computed: true, 58 }, 59 60 "dec": { 61 Type: schema.TypeString, 62 Computed: true, 63 }, 64 }, 65 } 66 } 67 68 func CreateID(d *schema.ResourceData, meta interface{}) error { 69 byteLength := d.Get("byte_length").(int) 70 bytes := make([]byte, byteLength) 71 72 n, err := rand.Reader.Read(bytes) 73 if n != byteLength { 74 return errors.New("generated insufficient random bytes") 75 } 76 if err != nil { 77 return errwrap.Wrapf("error generating random bytes: {{err}}", err) 78 } 79 80 b64Str := base64.RawURLEncoding.EncodeToString(bytes) 81 d.SetId(b64Str) 82 83 return RepopulateEncodings(d, meta) 84 } 85 86 func RepopulateEncodings(d *schema.ResourceData, _ interface{}) error { 87 prefix := d.Get("prefix").(string) 88 base64Str := d.Id() 89 90 bytes, err := base64.RawURLEncoding.DecodeString(base64Str) 91 if err != nil { 92 return errwrap.Wrapf("Error decoding ID: {{err}}", err) 93 } 94 95 b64StdStr := base64.StdEncoding.EncodeToString(bytes) 96 hexStr := hex.EncodeToString(bytes) 97 98 bigInt := big.Int{} 99 bigInt.SetBytes(bytes) 100 decStr := bigInt.String() 101 102 d.Set("b64", prefix+base64Str) 103 d.Set("b64_url", prefix+base64Str) 104 d.Set("b64_std", prefix+b64StdStr) 105 106 d.Set("hex", prefix+hexStr) 107 d.Set("dec", prefix+decStr) 108 109 return nil 110 }