Skip to content

Commit

Permalink
Before alter group make sure user still exists
Browse files Browse the repository at this point in the history
When there is no dependency between user and group or user is in
multiple groups and was removed before then terraform will fail. After this
commit we fix problem and during alter table we check if user still
exists in redshift.
  • Loading branch information
Lukas Budisky authored and Lukas Budisky committed Apr 22, 2022
1 parent 71656ee commit 0053db1
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions redshift/resource_redshift_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,26 @@ func setGroupName(tx *sql.Tx, d *schema.ResourceData) error {
return nil
}

func checkIfUserExists(tx *sql.Tx, name interface{}) (bool, error) {

username, ok := name.(string)
if !ok {
return false, fmt.Errorf("cannot convert username to string")
}

var result int
err := tx.QueryRow("SELECT 1 from pg_user_info WHERE usename=$1", username).Scan(&result)

switch err {
case sql.ErrNoRows:
return false, nil
case nil:
return false, fmt.Errorf("error reading info about user: %s", err)
}

return true, nil
}

func setUsersNames(tx *sql.Tx, db *DBConnection, d *schema.ResourceData) error {
if !d.HasChange(groupUsersAttr) {
return nil
Expand All @@ -226,13 +246,22 @@ func setUsersNames(tx *sql.Tx, db *DBConnection, d *schema.ResourceData) error {
if removedUsers.Len() > 0 {
removedUsersNamesSafe := []string{}
for _, name := range removedUsers.List() {
removedUsersNamesSafe = append(removedUsersNamesSafe, pq.QuoteIdentifier(name.(string)))
userExists, err := checkIfUserExists(tx, name)
if err != nil {
return err
}

if userExists {
removedUsersNamesSafe = append(removedUsersNamesSafe, pq.QuoteIdentifier(name.(string)))
}
}

sql := fmt.Sprintf("ALTER GROUP %s DROP USER %s", pq.QuoteIdentifier(groupName), strings.Join(removedUsersNamesSafe, ", "))
if len(removedUsersNamesSafe) > 0 {
sql := fmt.Sprintf("ALTER GROUP %s DROP USER %s", pq.QuoteIdentifier(groupName), strings.Join(removedUsersNamesSafe, ", "))

if _, err := tx.Exec(sql); err != nil {
return err
if _, err := tx.Exec(sql); err != nil {
return err
}
}
}

Expand Down

0 comments on commit 0053db1

Please sign in to comment.