Skip to content

Commit

Permalink
azurerm_mssql_server_transparent_data_encryption - Support for auto…
Browse files Browse the repository at this point in the history
…rotation of KV keys (#18523)
  • Loading branch information
aristosvo authored Oct 26, 2022
1 parent 89e8af6 commit b017646
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package migration

import (
"context"
"log"

"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
)

// Default: false for `auto_rotation_enabled`

var _ pluginsdk.StateUpgrade = MsSqlTransparentDataEncryptionV0ToV1{}

type MsSqlTransparentDataEncryptionV0ToV1 struct{}

func (d MsSqlTransparentDataEncryptionV0ToV1) Schema() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"server_id": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
},

"key_vault_key_id": {
Type: pluginsdk.TypeString,
Optional: true,
},
}
}

func (d MsSqlTransparentDataEncryptionV0ToV1) UpgradeFunc() pluginsdk.StateUpgraderFunc {
return func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) {
log.Printf("[DEBUG] Upgrading from Transparent Data Encryption V0 to V1..")
existing := rawState["auto_rotation_enabled"]
if existing == nil {
log.Printf("[DEBUG] Setting `auto_rotation_enabled` to `false`")
rawState["auto_rotation_enabled"] = false
}

log.Printf("[DEBUG] Upgraded from Transparent Data Encryption V0 to V1..")
return rawState, nil
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
keyVaultParser "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse"
keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/migration"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse"
mssqlValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
Expand Down Expand Up @@ -38,18 +39,30 @@ func resourceMsSqlTransparentDataEncryption() *pluginsdk.Resource {
Delete: pluginsdk.DefaultTimeout(30 * time.Minute),
},

SchemaVersion: 1,
StateUpgraders: pluginsdk.StateUpgrades(map[int]pluginsdk.StateUpgrade{
0: migration.MsSqlTransparentDataEncryptionV0ToV1{},
}),

Schema: map[string]*pluginsdk.Schema{
"server_id": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: mssqlValidate.ServerID,
},

"key_vault_key_id": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: keyVaultValidate.NestedItemId,
},

"auto_rotation_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: false,
},
},
}
}
Expand Down Expand Up @@ -87,8 +100,9 @@ func resourceMsSqlTransparentDataEncryptionCreateUpdate(d *pluginsdk.ResourceDat

// Set the SQL Server Key properties
serverKeyProperties := sql.ServerKeyProperties{
ServerKeyType: serverKeyType,
URI: &keyVaultKeyId,
ServerKeyType: serverKeyType,
URI: &keyVaultKeyId,
AutoRotationEnabled: utils.Bool(d.Get("auto_rotation_enabled").(bool)),
}
serverKey.ServerKeyProperties = &serverKeyProperties

Expand Down Expand Up @@ -121,8 +135,9 @@ func resourceMsSqlTransparentDataEncryptionCreateUpdate(d *pluginsdk.ResourceDat

// Service managed doesn't require a key name
encryptionProtectorProperties := sql.EncryptionProtectorProperties{
ServerKeyType: serverKeyType,
ServerKeyName: &serverKeyName,
ServerKeyType: serverKeyType,
ServerKeyName: &serverKeyName,
AutoRotationEnabled: utils.Bool(d.Get("auto_rotation_enabled").(bool)),
}

// Only create a server key if the properties have been set
Expand Down Expand Up @@ -185,16 +200,25 @@ func resourceMsSqlTransparentDataEncryptionRead(d *pluginsdk.ResourceData, meta
log.Printf("[INFO] Encryption protector key type is %s", resp.EncryptionProtectorProperties.ServerKeyType)

keyVaultKeyId := ""

autoRotationEnabled := false
// Only set the key type if it's an AKV key. For service managed, we can omit the setting the key_vault_key_id
if resp.EncryptionProtectorProperties != nil && resp.EncryptionProtectorProperties.ServerKeyType == sql.ServerKeyTypeAzureKeyVault {
log.Printf("[INFO] Setting Key Vault URI to %s", *resp.EncryptionProtectorProperties.URI)

keyVaultKeyId = *resp.EncryptionProtectorProperties.URI

// autoRotation is only for AKV keys
if resp.EncryptionProtectorProperties.AutoRotationEnabled != nil {
autoRotationEnabled = *resp.EncryptionProtectorProperties.AutoRotationEnabled
}
}

if err := d.Set("key_vault_key_id", keyVaultKeyId); err != nil {
return fmt.Errorf("setting key_vault_key_id`: %+v", err)
return fmt.Errorf("setting `key_vault_key_id`: %+v", err)
}

if err := d.Set("auto_rotation_enabled", autoRotationEnabled); err != nil {
return fmt.Errorf("setting `auto_rotation_enabled`: %+v", err)
}

return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,28 @@ func TestAccMsSqlServerTransparentDataEncryption_keyVault(t *testing.T) {
})
}

func TestAccMsSqlServerTransparentDataEncryption_autoRotate(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_mssql_server_transparent_data_encryption", "test")
r := MsSqlServerTransparentDataEncryptionResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.autoRotate(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
{
Config: r.keyVault(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func TestAccMsSqlServerTransparentDataEncryption_systemManaged(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_mssql_server_transparent_data_encryption", "test")
r := MsSqlServerTransparentDataEncryptionResource{}
Expand Down Expand Up @@ -88,7 +110,7 @@ func (MsSqlServerTransparentDataEncryptionResource) Exists(ctx context.Context,
return utils.Bool(resp.ID != nil), nil
}

func (r MsSqlServerTransparentDataEncryptionResource) keyVault(data acceptance.TestData) string {
func (r MsSqlServerTransparentDataEncryptionResource) baseKeyVault(data acceptance.TestData) string {
return fmt.Sprintf(`
%s
Expand Down Expand Up @@ -141,12 +163,30 @@ resource "azurerm_key_vault_key" "generated" {
azurerm_key_vault.test,
]
}
`, r.server(data), data.RandomStringOfLength(5))
}

func (r MsSqlServerTransparentDataEncryptionResource) keyVault(data acceptance.TestData) string {
return fmt.Sprintf(`
%s
resource "azurerm_mssql_server_transparent_data_encryption" "test" {
server_id = azurerm_mssql_server.test.id
key_vault_key_id = azurerm_key_vault_key.generated.id
}
`, r.server(data), data.RandomStringOfLength(5))
`, r.baseKeyVault(data))
}

func (r MsSqlServerTransparentDataEncryptionResource) autoRotate(data acceptance.TestData) string {
return fmt.Sprintf(`
%s
resource "azurerm_mssql_server_transparent_data_encryption" "test" {
server_id = azurerm_mssql_server.test.id
key_vault_key_id = azurerm_key_vault_key.generated.id
auto_rotation_enabled = true
}
`, r.baseKeyVault(data))
}

func (r MsSqlServerTransparentDataEncryptionResource) systemManaged(data acceptance.TestData) string {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ The following arguments are supported:

~> **NOTE:** If `server_id` denotes a secondary server deployed for disaster recovery purposes, then the `key_vault_key_id` should be the same key used for the primary server's transparent data encryption. Both primary and secondary servers should be encrypted with same key material.

* `auto_rotation_enabled` - (Optional) When enabled, the server will continuously check the key vault for any new versions of the key being used as the TDE protector. If a new version of the key is detected, the TDE protector on the server will be automatically rotated to the latest key version within 60 minutes.

## Attributes Reference

In addition to the Arguments listed above - the following Attributes are exported:
Expand Down

0 comments on commit b017646

Please sign in to comment.