Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce new 'random_integer' provider #12

Merged
merged 4 commits into from
Nov 7, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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_range": resourceRange(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Naming things is always tricky... when I first saw this name I expected that the result would be a random start/end segment of a list, or some such thing, since "range" makes me think of a sub-portion of a list.

What do you think about calling this random_integer, as a sibling of random_string?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had a similar thought. However, random_integer gives me the impression that it does not necessarily require a range but allows me to get any integer. I could also make min and max optional and set it to min=0 and max=INTEGER_MAX. 🧐

},
}
}
59 changes: 59 additions & 0 deletions random/resource_range.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package random

import (
"fmt"
"strconv"

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

func resourceRange() *schema.Resource {
return &schema.Resource{
Create: CreateRange,
Read: RepopulateRange,
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,
},
},
}
}

func CreateRange(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.SetId(strconv.Itoa(number))

return nil
}

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

import (
"fmt"
"testing"

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

func TestAccResourceRangeBasic(t *testing.T) {
t.Parallel()
resource.UnitTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testRandomRangeBasic,
Check: resource.ComposeTestCheckFunc(
testAccResourceRangeBasic("random_range.range_1"),
),
},
},
})
}

func testAccResourceRangeBasic(id string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[id]
result := rs.Primary.ID
if !ok {
return fmt.Errorf("Not found: %s", id)
}
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 (
testRandomRangeBasic = `
resource "random_range" "range_1" {
min = 1
max = 3
seed = "12345"
}
`
)
64 changes: 64 additions & 0 deletions website/docs/r/range.html.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
layout: "random"
page_title: "Random: random_range"
sidebar_current: "docs-random-resource-range"
description: |-
Generates a random integer value from a range.
---

# random\_range

The resource `random_range` 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_range" "priority" {
min = 1
max = 99999
keepers = {
# Generate a new pet name each time we switch to a new AMI id
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix documentation.

ami_id = "${var.listener_arn}"
}
}

resource "aws_alb_listener_rule" "main" {
listener_arn = "${var.listener_arn}"
priority = "${random_range.priority.id}"

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` - (int) The random range value.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It feels a little unintuitive to use id for this, since the result probably isn't an id in the usual sense we mean it.

We are required to call SetId to give Terraform something to track with, but I'd suggest that we consider that an undocumented implementation detail and instead publish a computed attribute called result which is documented here.

  priority     = "${random_range.priority.result}"

What do you think? (I chose result here again for consistency with random_string)

Copy link
Contributor Author

@bitbrain bitbrain Nov 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to stick to the notation of already existing providers (e.g. pet provider) which also populates an id attribute as a result.

Regardless, I agree with you, result should be it! 👍

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-range") %>>
<a href="/docs/providers/random/r/range.html">random_range</a>
</li>
</ul>
</li>
</ul>
Expand Down