Skip to content

Commit

Permalink
account: update grants in-place instead of remove/add method (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
igungor committed Feb 26, 2021
1 parent 1a28b37 commit 3c33319
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
36 changes: 34 additions & 2 deletions pkg/resources/account_grant.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,12 @@ var accountGrantSchema = map[string]*schema.Schema{
Description: "The privilege to grant on the account.",
Default: privilegeMonitorUsage,
ValidateFunc: validation.ValidatePrivilege(validAccountPrivileges.ToList(), true),
ForceNew: true,
},
"roles": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Description: "Grants privilege to these roles.",
ForceNew: true,
},
"with_grant_option": {
Type: schema.TypeBool,
Expand All @@ -53,6 +51,7 @@ func AccountGrant() *TerraformGrantResource {
Create: CreateAccountGrant,
Read: ReadAccountGrant,
Delete: DeleteAccountGrant,
Update: UpdateAccountGrant,

Schema: accountGrantSchema,
},
Expand Down Expand Up @@ -112,3 +111,36 @@ func DeleteAccountGrant(d *schema.ResourceData, meta interface{}) error {

return deleteGenericGrant(d, meta, builder)
}

// UpdateAccountGrant implements schema.UpdateFunc
func UpdateAccountGrant(d *schema.ResourceData, meta interface{}) error {
// for now the only thing we can update is roles.
// if nothing changed, nothing to update and we're done.
if !d.HasChanges("roles") {
return nil
}

rolesToAdd, rolesToRevoke := changeDiff(d, "roles")

grantID, err := grantIDFromString(d.Id())
if err != nil {
return err
}

builder := snowflake.AccountGrant()

// first revoke
err = deleteGenericGrantRolesAndShares(meta, builder, grantID.Privilege, rolesToRevoke, nil)
if err != nil {
return err
}

// then add
err = createGenericGrantRolesAndShares(meta, builder, grantID.Privilege, grantID.GrantOption, rolesToAdd, nil)
if err != nil {
return err
}

// done, refresh state
return ReadAccountGrant(d, meta)
}
10 changes: 10 additions & 0 deletions pkg/resources/grant_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -449,3 +449,13 @@ func formatCallableObjectName(callableName string, returnType string, arguments

return fmt.Sprintf(`%v(%v):%v`, callableName, strings.Join(argumentSignatures, ", "), returnType), argumentNames, argumentTypes
}

// changeDiff calculates roles/shares to add/revoke
func changeDiff(d *schema.ResourceData, key string) (toAdd []string, toRemove []string) {
o, n := d.GetChange(key)
oldSet := o.(*schema.Set)
newSet := n.(*schema.Set)
toAdd = expandStringList(newSet.Difference(oldSet).List())
toRemove = expandStringList(oldSet.Difference(newSet).List())
return
}

0 comments on commit 3c33319

Please sign in to comment.