forked from cyrilgdn/terraform-provider-postgresql
-
Notifications
You must be signed in to change notification settings - Fork 0
PLAT-1484 Add New Resource For Alter Role #1
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,211 @@ | ||
package postgresql | ||
|
||
import ( | ||
"database/sql" | ||
// "encoding/json" | ||
"fmt" | ||
"log" | ||
"strings" | ||
|
||
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" | ||
"github.com/lib/pq" | ||
) | ||
|
||
const ( | ||
getAlterRoleQuery = ` | ||
SELECT | ||
rolname as role, | ||
rolconfig as role_parameters | ||
FROM | ||
pg_catalog.pg_roles | ||
WHERE | ||
rolname = $1 | ||
` | ||
) | ||
|
||
func resourcePostgreSQLAlterRole() *schema.Resource { | ||
return &schema.Resource{ | ||
Create: PGResourceFunc(resourcePostgreSQLAlterRoleCreate), | ||
Read: PGResourceFunc(resourcePostgreSQLAlterRoleRead), | ||
Delete: PGResourceFunc(resourcePostgreSQLAlterRoleDelete), | ||
|
||
Schema: map[string]*schema.Schema{ | ||
"role_name": { | ||
Type: schema.TypeString, | ||
Required: true, | ||
ForceNew: true, | ||
Description: "The name of the role to alter the attributes of", | ||
}, | ||
"parameter_key": { | ||
Type: schema.TypeString, | ||
Required: true, | ||
ForceNew: true, | ||
Description: "The name of the parameter to alter on the role", | ||
}, | ||
"parameter_value": { | ||
Type: schema.TypeString, | ||
Required: true, | ||
ForceNew: true, | ||
Description: "The value of the parameter which is being set", | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
func resourcePostgreSQLAlterRoleRead(db *DBConnection, d *schema.ResourceData) error { | ||
if !db.featureSupported(featurePrivileges) { | ||
return fmt.Errorf( | ||
"postgresql_alter_role resource is not supported for this Postgres version (%s)", | ||
db.version, | ||
) | ||
} | ||
|
||
return readAlterRole(db, d) | ||
} | ||
|
||
func resourcePostgreSQLAlterRoleCreate(db *DBConnection, d *schema.ResourceData) error { | ||
if !db.featureSupported(featurePrivileges) { | ||
return fmt.Errorf( | ||
"postgresql_alter_role resource is not supported for this Postgres version (%s)", | ||
db.version, | ||
) | ||
} | ||
|
||
txn, err := startTransaction(db.client, "") | ||
if err != nil { | ||
return err | ||
} | ||
defer deferredRollback(txn) | ||
|
||
// Reset the role alterations before altering them again. | ||
if err = resetAlterRole(txn, d); err != nil { | ||
rymir marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return err | ||
} | ||
|
||
if err = alterRole(txn, d); err != nil { | ||
return err | ||
} | ||
|
||
if err = txn.Commit(); err != nil { | ||
return fmt.Errorf("could not commit transaction: %w", err) | ||
} | ||
|
||
d.SetId(generateAlterRoleID(d)) | ||
|
||
return readAlterRole(db, d) | ||
} | ||
|
||
func resourcePostgreSQLAlterRoleDelete(db *DBConnection, d *schema.ResourceData) error { | ||
if !db.featureSupported(featurePrivileges) { | ||
return fmt.Errorf( | ||
"postgresql_alter_role resource is not supported for this Postgres version (%s)", | ||
db.version, | ||
) | ||
} | ||
|
||
txn, err := startTransaction(db.client, "") | ||
if err != nil { | ||
return err | ||
} | ||
defer deferredRollback(txn) | ||
|
||
if err = resetAlterRole(txn, d); err != nil { | ||
return err | ||
} | ||
|
||
if err = txn.Commit(); err != nil { | ||
return fmt.Errorf("could not commit transaction: %w", err) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func readAlterRole(db QueryAble, d *schema.ResourceData) error { | ||
var ( | ||
roleName string | ||
roleParameters pq.ByteaArray | ||
) | ||
|
||
alterRoleID := d.Id() | ||
alterParameterKey := d.Get("parameter_key") | ||
|
||
values := []interface{}{ | ||
&roleName, | ||
&roleParameters, | ||
} | ||
|
||
err := db.QueryRow(getAlterRoleQuery, d.Get("role_name")).Scan(values...) | ||
switch { | ||
case err == sql.ErrNoRows: | ||
log.Printf("[WARN] PostgreSQL alter role (%q) not found", alterRoleID) | ||
d.SetId("") | ||
return nil | ||
case err != nil: | ||
return fmt.Errorf("error reading alter role: %w", err) | ||
} | ||
|
||
d.Set("parameter_key", alterParameterKey) | ||
d.Set("parameter_value", "") | ||
d.Set("role_name", roleName) | ||
d.SetId(generateAlterRoleID(d)) | ||
|
||
for _, v := range roleParameters { | ||
parameter := string(v) | ||
parameterKey := strings.Split(parameter, "=")[0] | ||
parameterValue := strings.Split(parameter, "=")[1] | ||
if parameterKey == alterParameterKey { | ||
d.Set("parameter_key", parameterKey) | ||
d.Set("parameter_value", parameterValue) | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func createAlterRoleQuery(d *schema.ResourceData) string { | ||
alterRole, _ := d.Get("role_name").(string) | ||
alterParameterKey, _ := d.Get("parameter_key").(string) | ||
alterParameterValue, _ := d.Get("parameter_value").(string) | ||
|
||
query := fmt.Sprintf( | ||
"ALTER ROLE %s SET %s TO %s", | ||
pq.QuoteIdentifier(alterRole), | ||
pq.QuoteIdentifier(alterParameterKey), | ||
pq.QuoteIdentifier(alterParameterValue), | ||
) | ||
|
||
return query | ||
} | ||
|
||
func createResetAlterRoleQuery(d *schema.ResourceData) string { | ||
alterRole, _ := d.Get("role_name").(string) | ||
alterParameterKey, _ := d.Get("parameter_key").(string) | ||
|
||
return fmt.Sprintf( | ||
"ALTER ROLE %s RESET %s", | ||
pq.QuoteIdentifier(alterRole), | ||
pq.QuoteIdentifier(alterParameterKey), | ||
) | ||
} | ||
|
||
func alterRole(txn *sql.Tx, d *schema.ResourceData) error { | ||
query := createAlterRoleQuery(d) | ||
log.Println(query) | ||
if _, err := txn.Exec(query); err != nil { | ||
return fmt.Errorf("could not execute alter query testing message: %w", err) | ||
} | ||
return nil | ||
} | ||
|
||
func resetAlterRole(txn *sql.Tx, d *schema.ResourceData) error { | ||
query := createResetAlterRoleQuery(d) | ||
fmt.Println(query) | ||
if _, err := txn.Exec(query); err != nil { | ||
return fmt.Errorf("could not execute alter reset query (%s): %w", query, err) | ||
} | ||
return nil | ||
} | ||
|
||
func generateAlterRoleID(d *schema.ResourceData) string { | ||
return strings.Join([]string{d.Get("role_name").(string), d.Get("parameter_key").(string), d.Get("parameter_value").(string)}, "_") | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
package postgresql | ||
|
||
import ( | ||
"database/sql" | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" | ||
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" | ||
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform" | ||
"github.com/lib/pq" | ||
) | ||
|
||
func TestCreateAlterRoleQuery(t *testing.T) { | ||
var roleName = "foo" | ||
var parameterKey = "bar" | ||
var parameterValue = "foo" | ||
|
||
cases := []struct { | ||
resource map[string]interface{} | ||
expected string | ||
}{ | ||
{ | ||
resource: map[string]interface{}{ | ||
"role_name": roleName, | ||
"parameter_key": parameterKey, | ||
"parameter_value": parameterValue, | ||
}, | ||
expected: fmt.Sprintf("ALTER ROLE %s SET %s TO %s", | ||
pq.QuoteIdentifier(roleName), | ||
pq.QuoteIdentifier(parameterKey), | ||
pq.QuoteIdentifier(parameterValue)), | ||
}, | ||
} | ||
|
||
for _, c := range cases { | ||
out := createAlterRoleQuery(schema.TestResourceDataRaw(t, resourcePostgreSQLAlterRole().Schema, c.resource)) | ||
if out != c.expected { | ||
t.Fatalf("Error matching output and expected: %#v vs %#v", out, c.expected) | ||
} | ||
} | ||
} | ||
|
||
func TestResetRoleQuery(t *testing.T) { | ||
var roleName = "foo" | ||
var parameterKey = "pgaudit.role" | ||
|
||
expected := fmt.Sprintf("ALTER ROLE %s RESET %s", pq.QuoteIdentifier(roleName), pq.QuoteIdentifier(parameterKey)) | ||
|
||
cases := []struct { | ||
resource map[string]interface{} | ||
}{ | ||
{ | ||
resource: map[string]interface{}{ | ||
"role_name": roleName, | ||
"parameter_key": parameterKey, | ||
}, | ||
}, | ||
} | ||
|
||
for _, c := range cases { | ||
out := createResetAlterRoleQuery(schema.TestResourceDataRaw(t, resourcePostgreSQLAlterRole().Schema, c.resource)) | ||
if out != expected { | ||
t.Fatalf("Error matching output and expected: %#v vs %#v", out, expected) | ||
} | ||
} | ||
} | ||
|
||
func TestAccPostgresqlAlterRole(t *testing.T) { | ||
skipIfNotAcc(t) | ||
|
||
config := getTestConfig(t) | ||
dsn := config.connStr("postgres") | ||
|
||
dbSuffix, teardown := setupTestDatabase(t, false, true) | ||
defer teardown() | ||
|
||
_, roleName := getTestDBNames(dbSuffix) | ||
|
||
parameterKey := "pgaudit.log" | ||
parameterValue := "ALL" | ||
|
||
testAccPostgresqlAlterRoleResources := fmt.Sprintf(` | ||
resource "postgresql_alter_role" "alter_role" { | ||
role_name = "%s" | ||
parameter_key = "%s" | ||
parameter_value = "%s" | ||
} | ||
`, roleName, parameterKey, parameterValue) | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { | ||
testAccPreCheck(t) | ||
testCheckCompatibleVersion(t, featurePrivileges) | ||
}, | ||
Providers: testAccProviders, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: testAccPostgresqlAlterRoleResources, | ||
Check: resource.ComposeTestCheckFunc( | ||
resource.TestCheckResourceAttr( | ||
"postgresql_alter_role.alter_role", "role_name", roleName), | ||
resource.TestCheckResourceAttr( | ||
"postgresql_alter_role.alter_role", "parameter_key", parameterKey), | ||
resource.TestCheckResourceAttr( | ||
"postgresql_alter_role.alter_role", "parameter_value", parameterValue), | ||
checkAlterRole(t, dsn, roleName, parameterKey, parameterValue), | ||
), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func checkAlterRole(t *testing.T, dsn, role string, parameterKey string, parameterValue string) resource.TestCheckFunc { | ||
return func(s *terraform.State) error { | ||
db, err := sql.Open("postgres", dsn) | ||
if err != nil { | ||
t.Fatalf("could to create connection pool: %v", err) | ||
} | ||
defer db.Close() | ||
|
||
roleParameter := fmt.Sprintf("%s=%s", parameterKey, parameterValue) | ||
var _rez int | ||
err = db.QueryRow(` | ||
SELECT 1 | ||
FROM pg_catalog.pg_roles | ||
WHERE rolname = $1 | ||
AND $2=ANY(rolconfig) | ||
`, role, roleParameter).Scan(&_rez) | ||
|
||
switch { | ||
case err == sql.ErrNoRows: | ||
return fmt.Errorf( | ||
"Role %s does not have the following attribute assigned %s", | ||
role, roleParameter, | ||
) | ||
|
||
case err != nil: | ||
t.Fatalf("could not check roles attributes: %v", err) | ||
} | ||
|
||
return nil | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.