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

Added additional option for the provider to fix the issue of printing the generated string in logs. #36

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
11 changes: 6 additions & 5 deletions random/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ func Provider() terraform.ResourceProvider {
Schema: map[string]*schema.Schema{},

ResourcesMap: map[string]*schema.Resource{
"random_id": resourceId(),
"random_shuffle": resourceShuffle(),
"random_pet": resourcePet(),
"random_string": resourceString(),
"random_integer": resourceInteger(),
"random_id": resourceId(),
"random_shuffle": resourceShuffle(),
"random_pet": resourcePet(),
"random_string": resourceString(),
"random_integer": resourceInteger(),
"random_password": resourcePassword(),
},
}
}
184 changes: 184 additions & 0 deletions random/resource_password.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package random

import (
"crypto/rand"
"math/big"
"sort"

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

func resourcePassword() *schema.Resource {
return &schema.Resource{
Create: CreatePassword,
Read: ReadPassword,
Delete: schema.RemoveFromState,
MigrateState: resourceRandomStringMigrateState,
SchemaVersion: 1,
Schema: map[string]*schema.Schema{
"keepers": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},

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

"special": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},

"upper": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},

"lower": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},

"number": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},

"min_numeric": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},

"min_upper": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},

"min_lower": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},

"min_special": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},

"override_special": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},

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

func CreatePassword(d *schema.ResourceData, meta interface{}) error {
const numChars = "0123456789"
const lowerChars = "abcdefghijklmnopqrstuvwxyz"
const upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var specialChars = "!@#$%&*()-_=+[]{}<>:?"

length := d.Get("length").(int)
upper := d.Get("upper").(bool)
minUpper := d.Get("min_upper").(int)
lower := d.Get("lower").(bool)
minLower := d.Get("min_lower").(int)
number := d.Get("number").(bool)
minNumeric := d.Get("min_numeric").(int)
special := d.Get("special").(bool)
minSpecial := d.Get("min_special").(int)
overrideSpecial := d.Get("override_special").(string)

if overrideSpecial != "" {
specialChars = overrideSpecial
}

var chars = string("")
if upper {
chars += upperChars
}
if lower {
chars += lowerChars
}
if number {
chars += numChars
}
if special {
chars += specialChars
}

minMapping := map[string]int{
numChars: minNumeric,
lowerChars: minLower,
upperChars: minUpper,
specialChars: minSpecial,
}
var result = make([]byte, 0, length)
for k, v := range minMapping {
s, err := generateRandomBytes(&k, v)
if err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
}
result = append(result, s...)
}
s, err := generateRandomBytes(&chars, length-len(result))
if err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
}
result = append(result, s...)
order := make([]byte, len(result))
if _, err := rand.Read(order); err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
}
sort.Slice(result, func(i, j int) bool {
return order[i] < order[j]
})

d.Set("result", string(result))
d.SetId("none")
return nil
}

func generateRandomPass(charSet *string, length int) ([]byte, error) {
bytes := make([]byte, length)
setLen := big.NewInt(int64(len(*charSet)))
for i := range bytes {
idx, err := rand.Int(rand.Reader, setLen)
if err != nil {
return nil, err
}
bytes[i] = (*charSet)[idx.Int64()]
}
return bytes, nil
}

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

import (
"fmt"
"regexp"
"testing"

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

func TestAccResourcePassword(t *testing.T) {
resource.UnitTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccResourcePasswordConfig,
Check: resource.ComposeTestCheckFunc(
testAccResourcePasswordCheck("random_password.foo", &customLens{
customLen: 12,
}),
testAccResourcePasswordCheck("random_password.bar", &customLens{
customLen: 32,
}),
testAccResourcePasswordCheck("random_password.three", &customLens{
customLen: 4,
}),
patternMatch("random_password.three", "!!!!"),
testAccResourcePasswordCheck("random_password.min", &customLens{
customLen: 12,
}),
regexMatch("random_password.min", regexp.MustCompile(`([a-z])`), 2),
regexMatch("random_password.min", regexp.MustCompile(`([A-Z])`), 3),
regexMatch("random_password.min", regexp.MustCompile(`([0-9])`), 4),
regexMatch("random_password.min", regexp.MustCompile(`([!#@])`), 1),
),
},
},
})
}

func testAccResourcePasswordCheck(id string, want *customLens) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[id]
if !ok {
return fmt.Errorf("Not found: %s", id)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}

customStr := rs.Primary.Attributes["result"]

if got, want := len(customStr), want.customLen; got != want {
return fmt.Errorf("custom password length is %d; want %d", got, want)
}

return nil
}
}

const (
testAccResourcePasswordConfig = `
resource "random_password" "foo" {
length = 12
}

resource "random_password" "bar" {
length = 32
}

resource "random_password" "three" {
length = 4
override_special = "!"
lower = false
upper = false
number = false
}

resource "random_password" "min" {
length = 12
override_special = "!#@"
min_lower = 2
min_upper = 3
min_special = 1
min_numeric = 4
}

`
)