Skip to content

Commit

Permalink
New resource "random_integer"
Browse files Browse the repository at this point in the history
This is similar to "random_string" but produces a single integer within a given range.
  • Loading branch information
bitbrain authored and apparentlymart committed Nov 7, 2017
1 parent e858d3c commit d97b869
Show file tree
Hide file tree
Showing 5 changed files with 195 additions and 0 deletions.
1 change: 1 addition & 0 deletions random/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func Provider() terraform.ResourceProvider {
"random_shuffle": resourceShuffle(),
"random_pet": resourcePet(),
"random_string": resourceString(),
"random_integer": resourceInteger(),
},
}
}
68 changes: 68 additions & 0 deletions random/resource_integer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package random

import (
"fmt"
"strconv"

"github.com/hashicorp/terraform/helper/schema"
)

func resourceInteger() *schema.Resource {
return &schema.Resource{
Create: CreateInteger,
Read: RepopulateInteger,
Delete: schema.RemoveFromState,

Schema: map[string]*schema.Schema{
"keepers": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},

"min": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},

"max": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},

"seed": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},

"result": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}

func CreateInteger(d *schema.ResourceData, meta interface{}) error {
min := d.Get("min").(int)
max := d.Get("max").(int)
seed := d.Get("seed").(string)

if max <= min {
return fmt.Errorf("Minimum value needs to be smaller than maximum value")
}
rand := NewRand(seed)
number := rand.Intn((max+1)-min) + min

d.Set("result", number)
d.SetId(strconv.Itoa(number))

return nil
}

func RepopulateInteger(d *schema.ResourceData, _ interface{}) error {
return nil
}
58 changes: 58 additions & 0 deletions random/resource_integer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package random

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccResourceIntegerBasic(t *testing.T) {
t.Parallel()
resource.UnitTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testRandomIntegerBasic,
Check: resource.ComposeTestCheckFunc(
testAccResourceIntegerBasic("random_integer.integer_1"),
),
},
},
})
}

func testAccResourceIntegerBasic(id string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[id]
if !ok {
return fmt.Errorf("Not found: %s", id)
}
result := rs.Primary.Attributes["result"]

if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}

if result == "" {
return fmt.Errorf("Result not found")
}

if result != "3" {
return fmt.Errorf("Invalid result %s. Seed does not result in correct value", result)
}
return nil
}
}

const (
testRandomIntegerBasic = `
resource "random_integer" "integer_1" {
min = 1
max = 3
seed = "12345"
}
`
)
65 changes: 65 additions & 0 deletions website/docs/r/integer.html.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
layout: "random"
page_title: "Random: random_integer"
sidebar_current: "docs-random-resource-integer"
description: |-
Generates a random integer values.
---

# random\_integer

The resource `random_integer` generates random values from a given range, described by the `min` and `max` attributes of a given resource.

This resource can be used in conjunction with resources that have
the `create_before_destroy` lifecycle flag set, to avoid conflicts with
unique names during the brief period where both the old and new resources
exist concurrently.

## Example Usage

The following example shows how to generate a random priority between 1 and 99999 for
a `aws_alb_listener_rule` resource:
```hcl
resource "random_integer" "priority" {
min = 1
max = 99999
keepers = {
# Generate a new integer each time we switch to a new listener ARN
listener_arn = "${var.listener_arn}"
}
}
resource "aws_alb_listener_rule" "main" {
listener_arn = "${var.listener_arn}"
priority = "${random_integer.priority.result}"
action {
type = "forward"
target_group_arn = "${var.target_group_arn}"
}
# ... (other aws_alb_listener_rule arguments) ...
}
```

The result of the above will set a random priority.

## Argument Reference

The following arguments are supported:

* `min` - (int) The minimum inclusive value of the range.

* `max` - (int) The maximum inclusive value of the range.

* `keepers` - (Optional) Arbitrary map of values that, when changed, will
trigger a new id to be generated. See
[the main provider documentation](../index.html) for more information.

* `seed` - (Optional) A custom seed to always produce the same value.

## Attribute Reference

The following attributes are supported:

* `id` - (string) An internal id.
* `result` - (int) The random Integer result.
3 changes: 3 additions & 0 deletions website/random.erb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
<li<%= sidebar_current("docs-random-resource-string") %>>
<a href="/docs/providers/random/r/string.html">random_string</a>
</li>
<li<%= sidebar_current("docs-random-resource-integer") %>>
<a href="/docs/providers/random/r/integer.html">random_integer</a>
</li>
</ul>
</li>
</ul>
Expand Down

0 comments on commit d97b869

Please sign in to comment.