From afe198104f503e13add510e5429b81cabb72908b Mon Sep 17 00:00:00 2001 From: Wojciech Inglot Date: Mon, 3 Jan 2022 10:04:00 +0100 Subject: [PATCH] Move the superuser/password validation to CustomizeDiff func --- redshift/resource_redshift_user.go | 11 ++++++++++- redshift/resource_redshift_user_test.go | 23 ++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/redshift/resource_redshift_user.go b/redshift/resource_redshift_user.go index 6e87e2f..37e133f 100644 --- a/redshift/resource_redshift_user.go +++ b/redshift/resource_redshift_user.go @@ -1,6 +1,7 @@ package redshift import ( + "context" "crypto/md5" "database/sql" "fmt" @@ -54,6 +55,15 @@ Amazon Redshift user accounts can only be created and dropped by a database supe Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, + CustomizeDiff: func(_ context.Context, d *schema.ResourceDiff, p interface{}) error { + isSuperuser := d.Get(userSuperuserAttr).(bool) + password, hasPassword := d.GetOk(userPasswordAttr) + if isSuperuser && (!hasPassword || password.(string) == "") { + return fmt.Errorf("Users that are superusers must define a password.") + } + + return nil + }, Schema: map[string]*schema.Schema{ userNameAttr: { @@ -109,7 +119,6 @@ Amazon Redshift user accounts can only be created and dropped by a database supe }, userSuperuserAttr: { ConflictsWith: []string{userSyslogAccessAttr}, - RequiredWith: []string{userPasswordAttr}, Type: schema.TypeBool, Optional: true, Default: false, diff --git a/redshift/resource_redshift_user_test.go b/redshift/resource_redshift_user_test.go index 6d0e523..3d73b49 100644 --- a/redshift/resource_redshift_user_test.go +++ b/redshift/resource_redshift_user_test.go @@ -201,7 +201,28 @@ resource "redshift_user" "superuser" { Steps: []resource.TestStep{ { Config: config, - ExpectError: regexp.MustCompile("\"superuser\": all of `password,superuser` must be specified"), + ExpectError: regexp.MustCompile("Users that are superusers must define a password."), + }, + }, + }) +} + +func TestAccRedshiftUser_SuperuserFalseDoesntRequiresPassword(t *testing.T) { + userName := strings.ReplaceAll(acctest.RandomWithPrefix("tf_acc_superuser"), "-", "_") + config := fmt.Sprintf(` +resource "redshift_user" "superuser" { + name = %[1]q + superuser = false +} +`, userName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckRedshiftUserDestroy, + Steps: []resource.TestStep{ + { + Config: config, }, }, })