Skip to content
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

New resource: mssql_database_permissions #70

Open
wants to merge 4 commits into
base: master
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,6 @@ terraform-provider-mssql
terraform-provider-mssql.log
terraform-provider-mssql.exe
/.devcontainer/


vendor
56 changes: 56 additions & 0 deletions docs/resources/database_permissions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# mssql_database_permissions

The `mssql_database_permissions` resource manages user permissions on a SQL Server.

## Example Usage

```hcl
resource "mssql_database_permissions" "example" {
server {
host = "example-sql-server.database.windows.net"
azure_login {}
}
database = "example"
principal_id = 1
permissions = [
"EXECUTE",
"UPDATE",
"INSERT",
]
}
```

## Argument Reference

The following arguments are supported:

* `server` - (Required) Server and login details for the SQL Server. The attributes supported in the `server` block is detailed below. Changing this forces a new resource to be created.
* `database` - (Required) The name of the database to operate on. Changing this forces a new resource to be created.
* `principal_id` - (Required) The principal ID of the user permissions are managed for. Changing this forces a new resource to be created.
* `permissions` - (Required) List of permissions to grant to the user. Changing this forces a new resource to be created.

The `server` block supports the following arguments:

* `host` - (Required) The host of the SQL Server. Changing this forces a new resource to be created.
* `port` - (Optional) The port of the SQL Server. Defaults to `1433`. Changing this forces a new resource to be created.
* `login` - (Optional) SQL Server login for managing the database resources. The attributes supported in the `login` block is detailed below.
* `azure_login` - (Optional) Azure AD login for managing the database resources. The attributes supported in the `azure_login` block is detailed below.
* `azuread_default_chain_auth` - (Optional) Use a chain of strategies for authenticating when managing the database resources. This auth strategy is very similar to how the Azure CLI authenticates. For more information, see [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#configure-defaultazurecredential). This block has no attributes.
* `azuread_managed_identity_auth` - (Optional) Use a managed identity for authenticating when managing the database resources. This is mainly useful for specifying a user-assigned managed identity. The attributes supported in the `azuread_managed_identity_auth` block is detailed below.

The `login` block supports the following arguments:

* `username` - (Required) The username of the SQL Server login. Can also be sourced from the `MSSQL_USERNAME` environment variable.
* `password` - (Required) The password of the SQL Server login. Can also be sourced from the `MSSQL_PASSWORD` environment variable.

The `azure_login` block supports the following arguments:

* `tenant_id` - (Required) The tenant ID of the principal used to login to the SQL Server. Can also be sourced from the `MSSQL_TENANT_ID` environment variable.
* `client_id` - (Required) The client ID of the principal used to login to the SQL Server. Can also be sourced from the `MSSQL_CLIENT_ID` environment variable.
* `client_secret` - (Required) The client secret of the principal used to login to the SQL Server. Can also be sourced from the `MSSQL_CLIENT_SECRET` environment variable.

The `azuread_managed_identity_auth` block supports the following arguments:

* `user_id` - (Optional) Id of a user-assigned managed identity to assume. Omitting this property instructs the provider to assume a system-assigned managed identity.

-> Only one of `login`, `azure_login`, `azuread_default_chain_auth` and `azuread_managed_identity_auth` can be specified.
25 changes: 13 additions & 12 deletions mssql/const.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package mssql

const (
serverProp = "server"
databaseProp = "database"
principalIdProp = "principal_id"
usernameProp = "username"
objectIdProp = "object_id"
passwordProp = "password"
sidStrProp = "sid"
clientIdProp = "client_id"
authenticationTypeProp = "authentication_type"
defaultSchemaProp = "default_schema"
defaultSchemaPropDefault = "dbo"
rolesProp = "roles"
serverProp = "server"
databaseProp = "database"
principalIdProp = "principal_id"
usernameProp = "username"
objectIdProp = "object_id"
passwordProp = "password"
sidStrProp = "sid"
clientIdProp = "client_id"
authenticationTypeProp = "authentication_type"
defaultSchemaProp = "default_schema"
defaultSchemaPropDefault = "dbo"
rolesProp = "roles"
permissionsProp = "permissions"
)
7 changes: 7 additions & 0 deletions mssql/model/database_permissions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package model

type DatabasePermissions struct {
DatabaseName string
PrincipalID int
Permissions []string
}
112 changes: 57 additions & 55 deletions mssql/provider.go
Original file line number Diff line number Diff line change
@@ -1,91 +1,93 @@
package mssql

import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"io"
"os"
"github.com/betr-io/terraform-provider-mssql/mssql/model"
"github.com/betr-io/terraform-provider-mssql/sql"
"time"
"context"
"fmt"
"io"
"os"
"time"

"github.com/betr-io/terraform-provider-mssql/mssql/model"
"github.com/betr-io/terraform-provider-mssql/sql"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

type mssqlProvider struct {
factory model.ConnectorFactory
logger *zerolog.Logger
factory model.ConnectorFactory
logger *zerolog.Logger
}

const (
providerLogFile = "terraform-provider-mssql.log"
providerLogFile = "terraform-provider-mssql.log"
)

var (
defaultTimeout = schema.DefaultTimeout(30 * time.Second)
defaultTimeout = schema.DefaultTimeout(30 * time.Second)
)

func New(version, commit string) func() *schema.Provider {
return func() *schema.Provider {
return Provider(sql.GetFactory())
}
return func() *schema.Provider {
return Provider(sql.GetFactory())
}
}

func Provider(factory model.ConnectorFactory) *schema.Provider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"debug": {
Type: schema.TypeBool,
Description: fmt.Sprintf("Enable provider debug logging (logs to file %s)", providerLogFile),
Optional: true,
Default: false,
},
},
ResourcesMap: map[string]*schema.Resource{
"mssql_login": resourceLogin(),
"mssql_user": resourceUser(),
},
DataSourcesMap: map[string]*schema.Resource{},
ConfigureContextFunc: func(ctx context.Context, data *schema.ResourceData) (interface{}, diag.Diagnostics) {
return providerConfigure(ctx, data, factory)
},
}
return &schema.Provider{
Schema: map[string]*schema.Schema{
"debug": {
Type: schema.TypeBool,
Description: fmt.Sprintf("Enable provider debug logging (logs to file %s)", providerLogFile),
Optional: true,
Default: false,
},
},
ResourcesMap: map[string]*schema.Resource{
"mssql_database_permissions": resourceDatabasePermissions(),
"mssql_login": resourceLogin(),
"mssql_user": resourceUser(),
},
DataSourcesMap: map[string]*schema.Resource{},
ConfigureContextFunc: func(ctx context.Context, data *schema.ResourceData) (interface{}, diag.Diagnostics) {
return providerConfigure(ctx, data, factory)
},
}
}

func providerConfigure(ctx context.Context, data *schema.ResourceData, factory model.ConnectorFactory) (model.Provider, diag.Diagnostics) {
isDebug := data.Get("debug").(bool)
logger := newLogger(isDebug)
isDebug := data.Get("debug").(bool)
logger := newLogger(isDebug)

logger.Info().Msg("Created provider")
logger.Info().Msg("Created provider")

return mssqlProvider{factory: factory, logger: logger}, nil
return mssqlProvider{factory: factory, logger: logger}, nil
}

func (p mssqlProvider) GetConnector(prefix string, data *schema.ResourceData) (interface{}, error) {
return p.factory.GetConnector(prefix, data)
return p.factory.GetConnector(prefix, data)
}

func (p mssqlProvider) ResourceLogger(resource, function string) zerolog.Logger {
return p.logger.With().Str("resource", resource).Str("func", function).Logger()
return p.logger.With().Str("resource", resource).Str("func", function).Logger()
}

func (p mssqlProvider) DataSourceLogger(datasource, function string) zerolog.Logger {
return p.logger.With().Str("datasource", datasource).Str("func", function).Logger()
return p.logger.With().Str("datasource", datasource).Str("func", function).Logger()
}

func newLogger(isDebug bool) *zerolog.Logger {
var writer io.Writer = nil
logLevel := zerolog.Disabled
if isDebug {
f, err := os.OpenFile(providerLogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Err(err).Msg("error opening file")
}
writer = f
logLevel = zerolog.DebugLevel
}
logger := zerolog.New(writer).Level(logLevel).With().Timestamp().Logger()
return &logger
var writer io.Writer = nil
logLevel := zerolog.Disabled
if isDebug {
f, err := os.OpenFile(providerLogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Err(err).Msg("error opening file")
}
writer = f
logLevel = zerolog.DebugLevel
}
logger := zerolog.New(writer).Level(logLevel).With().Timestamp().Logger()
return &logger
}
Loading