github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/random/resource_id.go (about)

     1  package random
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/base64"
     6  	"encoding/hex"
     7  	"fmt"
     8  	"math/big"
     9  
    10  	"github.com/hashicorp/terraform/helper/schema"
    11  )
    12  
    13  func resourceId() *schema.Resource {
    14  	return &schema.Resource{
    15  		Create: CreateID,
    16  		Read:   stubRead,
    17  		Delete: stubDelete,
    18  
    19  		Schema: map[string]*schema.Schema{
    20  			"keepers": &schema.Schema{
    21  				Type:     schema.TypeMap,
    22  				Optional: true,
    23  				ForceNew: true,
    24  			},
    25  
    26  			"byte_length": &schema.Schema{
    27  				Type:     schema.TypeInt,
    28  				Required: true,
    29  				ForceNew: true,
    30  			},
    31  
    32  			"b64": &schema.Schema{
    33  				Type:     schema.TypeString,
    34  				Computed: true,
    35  			},
    36  
    37  			"hex": &schema.Schema{
    38  				Type:     schema.TypeString,
    39  				Computed: true,
    40  			},
    41  
    42  			"dec": &schema.Schema{
    43  				Type:     schema.TypeString,
    44  				Computed: true,
    45  			},
    46  		},
    47  	}
    48  }
    49  
    50  func CreateID(d *schema.ResourceData, meta interface{}) error {
    51  
    52  	byteLength := d.Get("byte_length").(int)
    53  	bytes := make([]byte, byteLength)
    54  
    55  	n, err := rand.Reader.Read(bytes)
    56  	if n != byteLength {
    57  		return fmt.Errorf("generated insufficient random bytes")
    58  	}
    59  	if err != nil {
    60  		return fmt.Errorf("error generating random bytes: %s", err)
    61  	}
    62  
    63  	b64Str := base64.RawURLEncoding.EncodeToString(bytes)
    64  	hexStr := hex.EncodeToString(bytes)
    65  
    66  	int := big.Int{}
    67  	int.SetBytes(bytes)
    68  	decStr := int.String()
    69  
    70  	d.SetId(b64Str)
    71  	d.Set("b64", b64Str)
    72  	d.Set("hex", hexStr)
    73  	d.Set("dec", decStr)
    74  
    75  	return nil
    76  }