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

     1  package random
     2  
     3  import (
     4  	"github.com/hashicorp/terraform/helper/schema"
     5  )
     6  
     7  func resourceShuffle() *schema.Resource {
     8  	return &schema.Resource{
     9  		Create: CreateShuffle,
    10  		Read:   stubRead,
    11  		Delete: stubDelete,
    12  
    13  		Schema: map[string]*schema.Schema{
    14  			"keepers": &schema.Schema{
    15  				Type:     schema.TypeMap,
    16  				Optional: true,
    17  				ForceNew: true,
    18  			},
    19  
    20  			"seed": &schema.Schema{
    21  				Type:     schema.TypeString,
    22  				Optional: true,
    23  				ForceNew: true,
    24  			},
    25  
    26  			"input": &schema.Schema{
    27  				Type:     schema.TypeList,
    28  				Required: true,
    29  				ForceNew: true,
    30  				Elem: &schema.Schema{
    31  					Type: schema.TypeString,
    32  				},
    33  			},
    34  
    35  			"result": &schema.Schema{
    36  				Type:     schema.TypeList,
    37  				Computed: true,
    38  				Elem: &schema.Schema{
    39  					Type: schema.TypeString,
    40  				},
    41  			},
    42  
    43  			"result_count": &schema.Schema{
    44  				Type:     schema.TypeInt,
    45  				Optional: true,
    46  				ForceNew: true,
    47  			},
    48  		},
    49  	}
    50  }
    51  
    52  func CreateShuffle(d *schema.ResourceData, meta interface{}) error {
    53  	input := d.Get("input").([]interface{})
    54  	seed := d.Get("seed").(string)
    55  
    56  	resultCount := d.Get("result_count").(int)
    57  	if resultCount == 0 {
    58  		resultCount = len(input)
    59  	}
    60  	result := make([]interface{}, 0, resultCount)
    61  
    62  	rand := NewRand(seed)
    63  
    64  	// Keep producing permutations until we fill our result
    65  Batches:
    66  	for {
    67  		perm := rand.Perm(len(input))
    68  
    69  		for _, i := range perm {
    70  			result = append(result, input[i])
    71  
    72  			if len(result) >= resultCount {
    73  				break Batches
    74  			}
    75  		}
    76  	}
    77  
    78  	d.SetId("-")
    79  	d.Set("result", result)
    80  
    81  	return nil
    82  }