Skip to content

Support role configuration parameters #305

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
115 changes: 115 additions & 0 deletions postgresql/resource_postgresql_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,23 @@ const (
roleSearchPathAttr = "search_path"
roleStatementTimeoutAttr = "statement_timeout"
roleAssumeRoleAttr = "assume_role"
roleParameterAttr = "parameter"
roleParameterNameAttr = "name"
roleParameterValueAttr = "value"
roleParameterQuoteAttr = "quote"

// Deprecated options
roleDepEncryptedAttr = "encrypted"
)

// These parameters have discrete attributes, so they are not supported by the parameter block
var ignoredRoleConfigurationParameters = []string{
roleSearchPathAttr,
roleIdleInTransactionSessionTimeoutAttr,
roleStatementTimeoutAttr,
"role",
}

func resourcePostgreSQLRole() *schema.Resource {
return &schema.Resource{
Create: PGResourceFunc(resourcePostgreSQLRoleCreate),
Expand Down Expand Up @@ -173,6 +185,36 @@ func resourcePostgreSQLRole() *schema.Resource {
Optional: true,
Description: "Role to switch to at login",
},
roleParameterAttr: {
Type: schema.TypeSet,
Optional: true,
Description: "Configuration parameters",
Elem: resourcePostgreSQLRoleConfigurationParameter(),
},
},
}
}

func resourcePostgreSQLRoleConfigurationParameter() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
roleParameterNameAttr: {
Type: schema.TypeString,
Required: true,
Description: "Name of the configuration parameter to set",
ValidateFunc: validation.StringNotInSlice(ignoredRoleConfigurationParameters, true),
},
roleParameterValueAttr: {
Type: schema.TypeString,
Required: true,
Description: "Value of the configuration parameter",
},
roleParameterQuoteAttr: {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Quote the parameter value as a literal",
},
},
}
}
Expand Down Expand Up @@ -311,6 +353,10 @@ func resourcePostgreSQLRoleCreate(db *DBConnection, d *schema.ResourceData) erro
return err
}

if err = setConfigurationParameters(txn, d); err != nil {
return err
}

if err = txn.Commit(); err != nil {
return fmt.Errorf("could not commit transaction: %w", err)
}
Expand Down Expand Up @@ -480,6 +526,8 @@ func resourcePostgreSQLRoleReadImpl(db *DBConnection, d *schema.ResourceData) er
}

d.Set(rolePasswordAttr, password)

d.Set(roleParameterAttr, readRoleParameters(roleConfig, d.Get(roleParameterAttr).(*schema.Set)))
return nil
}

Expand Down Expand Up @@ -547,6 +595,28 @@ func readAssumeRole(roleConfig pq.ByteaArray) string {
return res
}

func readRoleParameters(roleConfig pq.ByteaArray, existingParams *schema.Set) *schema.Set {
params := make([]interface{}, 0)
for _, v := range roleConfig {
tokens := strings.Split(string(v), "=")
if !sliceContainsStr(ignoredRoleConfigurationParameters, tokens[0]) {
quote := true
for _, p := range existingParams.List() {
existingParam := p.(map[string]interface{})
if existingParam[roleParameterNameAttr].(string) == tokens[0] {
quote = existingParam[roleParameterQuoteAttr].(bool)
}
}
params = append(params, map[string]interface{}{
roleParameterNameAttr: tokens[0],
roleParameterValueAttr: tokens[1],
roleParameterQuoteAttr: quote,
})
}
}
return schema.NewSet(schema.HashResource(resourcePostgreSQLRoleConfigurationParameter()), params)
}

// readRolePassword reads password either from Postgres if admin user is a superuser
// or only from Terraform state.
func readRolePassword(db *DBConnection, d *schema.ResourceData, roleCanLogin bool) (string, error) {
Expand Down Expand Up @@ -689,6 +759,10 @@ func resourcePostgreSQLRoleUpdate(db *DBConnection, d *schema.ResourceData) erro
return err
}

if err = setConfigurationParameters(txn, d); err != nil {
return err
}

if err = txn.Commit(); err != nil {
return fmt.Errorf("could not commit transaction: %w", err)
}
Expand Down Expand Up @@ -961,6 +1035,47 @@ func grantRoles(txn *sql.Tx, d *schema.ResourceData) error {
return nil
}

func setConfigurationParameters(txn *sql.Tx, d *schema.ResourceData) error {
role := d.Get(roleNameAttr).(string)
if d.HasChange(roleParameterAttr) {
o, n := d.GetChange(roleParameterAttr)
oldParams := o.(*schema.Set)
newParams := n.(*schema.Set)
for _, p := range oldParams.List() {
if !newParams.Contains(p) {
param := p.(map[string]interface{})
query := fmt.Sprintf(
"ALTER ROLE %s RESET %s",
pq.QuoteIdentifier(role),
pq.QuoteIdentifier(param[roleParameterNameAttr].(string)))
log.Printf("[DEBUG] setConfigurationParameters: %s", query)
if _, err := txn.Exec(query); err != nil {
return err
}
}
}
for _, p := range newParams.List() {
if !oldParams.Contains(p) {
param := p.(map[string]interface{})
value := param[roleParameterValueAttr].(string)
if param[roleParameterQuoteAttr].(bool) {
value = pq.QuoteLiteral(value)
}
query := fmt.Sprintf(
"ALTER ROLE %s SET %s TO %s",
pq.QuoteIdentifier(role),
pq.QuoteIdentifier(param[roleParameterNameAttr].(string)),
value)
log.Printf("[DEBUG] setConfigurationParameters: %s", query)
if _, err := txn.Exec(query); err != nil {
return err
}
}
}
}
return nil
}

func alterSearchPath(txn *sql.Tx, d *schema.ResourceData) error {
role := d.Get(roleNameAttr).(string)
searchPathInterface := d.Get(roleSearchPathAttr).([]interface{})
Expand Down
214 changes: 214 additions & 0 deletions postgresql/resource_postgresql_role_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,184 @@ resource "postgresql_role" "update_role" {
})
}

func TestAccPostgresqlRole_ConfigurationParameters(t *testing.T) {

var configRoles = `
resource "postgresql_role" "role" {
name = "role1"
%s
}

resource "postgresql_role" "role_created_with_params" {
name = "role2"

parameter {
name = "client_min_messages"
value = "debug"
}
}
`
configParameterA := `
parameter {
name = "client_min_messages"
value = "%s"
}
`
configParameterB := `
parameter {
name = "maintenance_work_mem"
value = "10000"
quote = false
}
`

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testCheckCompatibleVersion(t, featurePrivileges)
},
Providers: testAccProviders,
CheckDestroy: testAccCheckPostgresqlRoleDestroy,
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(configRoles, ""),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "0"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "name", "role2"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.#", "1"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.0.name", "client_min_messages"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.0.value", "debug"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{}),
testAccCheckRoleHasConfigurationParameters("role2", map[string]string{"client_min_messages": "debug"}),
),
},
{
Config: fmt.Sprintf(configRoles, fmt.Sprintf(configParameterA, "notice")+configParameterB),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "2"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.name", "client_min_messages"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.value", "notice"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.1.name", "maintenance_work_mem"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.1.value", "10000"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "name", "role2"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.#", "1"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{
"client_min_messages": "notice",
"maintenance_work_mem": "10000",
}),
),
},
{
Config: fmt.Sprintf(configRoles, fmt.Sprintf(configParameterA, "error")),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.name", "client_min_messages"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.value", "error"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "name", "role2"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.#", "1"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{"client_min_messages": "error"}),
),
},
{
Config: fmt.Sprintf(configRoles, ""),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "0"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "name", "role2"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.#", "1"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.0.name", "client_min_messages"),
resource.TestCheckResourceAttr("postgresql_role.role_created_with_params", "parameter.0.value", "debug"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{}),
testAccCheckRoleHasConfigurationParameters("role2", map[string]string{"client_min_messages": "debug"}),
),
},
},
})
}

func TestAccPostgresqlRole_ConfigurationParameters_WithExplicitParameterAttrs(t *testing.T) {
var configRole = `
resource "postgresql_role" "role" {
name = "role1"
search_path = ["here","there"]
idle_in_transaction_session_timeout = 300
statement_timeout = 100
assume_role = "other_role"
%s
}
`
configParameterA := `
parameter {
name = "client_min_messages"
value = "%s"
}
`
configParameterB := `
parameter {
name = "maintenance_work_mem"
value = "10000"
quote = false
}
`

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testCheckCompatibleVersion(t, featurePrivileges)
},
Providers: testAccProviders,
CheckDestroy: testAccCheckPostgresqlRoleDestroy,
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(configRole, fmt.Sprintf(configParameterA, "debug")),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.name", "client_min_messages"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.value", "debug"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{"client_min_messages": "debug"}),
),
},
{
Config: fmt.Sprintf(configRole, fmt.Sprintf(configParameterA, "notice")+configParameterB),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "2"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.name", "client_min_messages"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.value", "notice"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.1.name", "maintenance_work_mem"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.1.value", "10000"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{
"client_min_messages": "notice",
"maintenance_work_mem": "10000",
}),
),
},
{
Config: fmt.Sprintf(configRole, fmt.Sprintf(configParameterA, "error")),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.name", "client_min_messages"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.0.value", "error"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{"client_min_messages": "error"}),
),
},
{
Config: fmt.Sprintf(configRole, ""),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_role.role", "name", "role1"),
resource.TestCheckResourceAttr("postgresql_role.role", "parameter.#", "0"),
testAccCheckRoleHasConfigurationParameters("role1", map[string]string{}),
),
},
},
})
}

// Test to create a role with admin user (usually postgres) granted to it
// There were a bug on RDS like setup (with a non-superuser postgres role)
// where it couldn't delete the role in this case.
Expand Down Expand Up @@ -295,6 +473,42 @@ func checkRoleExists(client *Client, roleName string) (bool, error) {
return true, nil
}

func testAccCheckRoleHasConfigurationParameters(roleName string, parameters map[string]string) resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*Client)
db, err := client.Connect()
if err != nil {
return err
}
rows, err := db.Query("SELECT UNNEST(rolconfig) FROM pg_roles WHERE rolname=$1", roleName)
if err != nil {
return err
}
setParameters := make(map[string]string)
for rows.Next() {
var param string
if err := rows.Scan(&param); err != nil {
return err
}
split := strings.Split(param, "=")
if !sliceContainsStr(ignoredRoleConfigurationParameters, split[0]) {
setParameters[split[0]] = split[1]
}
}
if len(parameters) != len(setParameters) {
return fmt.Errorf("expected role %s to have %d configuration parameters, found %d", roleName, len(parameters), len(setParameters))
}
for k := range parameters {
if parameters[k] != setParameters[k] {
return fmt.Errorf(
"expected configuration parameter %s for role %s to have value \"%s\", found \"%s\"",
k, roleName, parameters[k], setParameters[k])
}
}
return nil
}
}

func testAccCheckRoleCanLogin(t *testing.T, role, password string) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := getTestConfig(t)
Expand Down
Loading