diff --git a/azurerm/internal/services/mysql/client/client.go b/azurerm/internal/services/mysql/client/client.go index fca16a5ad81f..d5d78689d17a 100644 --- a/azurerm/internal/services/mysql/client/client.go +++ b/azurerm/internal/services/mysql/client/client.go @@ -10,6 +10,7 @@ type Client struct { DatabasesClient *mysql.DatabasesClient FirewallRulesClient *mysql.FirewallRulesClient ServersClient *mysql.ServersClient + ServerKeysClient *mysql.ServerKeysClient ServerSecurityAlertPoliciesClient *mysql.ServerSecurityAlertPoliciesClient VirtualNetworkRulesClient *mysql.VirtualNetworkRulesClient ServerAdministratorsClient *mysql.ServerAdministratorsClient @@ -28,6 +29,9 @@ func NewClient(o *common.ClientOptions) *Client { ServersClient := mysql.NewServersClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&ServersClient.Client, o.ResourceManagerAuthorizer) + ServerKeysClient := mysql.NewServerKeysClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&ServerKeysClient.Client, o.ResourceManagerAuthorizer) + serverSecurityAlertPoliciesClient := mysql.NewServerSecurityAlertPoliciesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&serverSecurityAlertPoliciesClient.Client, o.ResourceManagerAuthorizer) @@ -42,6 +46,7 @@ func NewClient(o *common.ClientOptions) *Client { DatabasesClient: &DatabasesClient, FirewallRulesClient: &FirewallRulesClient, ServersClient: &ServersClient, + ServerKeysClient: &ServerKeysClient, ServerSecurityAlertPoliciesClient: &serverSecurityAlertPoliciesClient, VirtualNetworkRulesClient: &VirtualNetworkRulesClient, ServerAdministratorsClient: &serverAdministratorsClient, diff --git a/azurerm/internal/services/mysql/mysql_configuration_resource.go b/azurerm/internal/services/mysql/mysql_configuration_resource.go index 3bb2cfb03d3c..2c5f443da8be 100644 --- a/azurerm/internal/services/mysql/mysql_configuration_resource.go +++ b/azurerm/internal/services/mysql/mysql_configuration_resource.go @@ -44,7 +44,7 @@ func resourceArmMySQLConfiguration() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.MysqlServerServerName, + ValidateFunc: validate.MySQLServerName, }, "value": { diff --git a/azurerm/internal/services/mysql/mysql_database_resource.go b/azurerm/internal/services/mysql/mysql_database_resource.go index ed3c25d11918..6fb9148380c2 100644 --- a/azurerm/internal/services/mysql/mysql_database_resource.go +++ b/azurerm/internal/services/mysql/mysql_database_resource.go @@ -46,7 +46,7 @@ func resourceArmMySqlDatabase() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.MysqlServerServerName, + ValidateFunc: validate.MySQLServerName, }, "charset": { diff --git a/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go b/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go index cbf16bbf0402..3bd3eedd8e7e 100644 --- a/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go +++ b/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go @@ -46,7 +46,7 @@ func resourceArmMySqlFirewallRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.MysqlServerServerName, + ValidateFunc: validate.MySQLServerName, }, "start_ip_address": { diff --git a/azurerm/internal/services/mysql/mysql_server_key_resource.go b/azurerm/internal/services/mysql/mysql_server_key_resource.go new file mode 100644 index 000000000000..6b916847321d --- /dev/null +++ b/azurerm/internal/services/mysql/mysql_server_key_resource.go @@ -0,0 +1,197 @@ +package mysql + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2019-09-01/keyvault" + "github.com/Azure/azure-sdk-for-go/services/mysql/mgmt/2020-01-01/mysql" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/locks" + keyVaultParse "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/keyvault/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/validate" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmMySQLServerKey() *schema.Resource { + return &schema.Resource{ + Create: resourceArmMySQLServerKeyCreateUpdate, + Read: resourceArmMySQLServerKeyRead, + Update: resourceArmMySQLServerKeyCreateUpdate, + Delete: resourceArmMySQLServerKeyDelete, + + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.MySQLServerKeyID(id) + return err + }), + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(60 * time.Minute), + Read: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(60 * time.Minute), + Delete: schema.DefaultTimeout(60 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "server_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.MySQLServerID, + }, + + "key_vault_key_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: azure.ValidateKeyVaultChildId, + }, + }, + } +} + +func getMySQLServerKeyName(ctx context.Context, vaultsClient *keyvault.VaultsClient, keyVaultKeyURI string) (*string, error) { + keyVaultKeyID, err := azure.ParseKeyVaultChildID(keyVaultKeyURI) + if err != nil { + return nil, err + } + keyVaultIDRaw, err := azure.GetKeyVaultIDFromBaseUrl(ctx, vaultsClient, keyVaultKeyID.KeyVaultBaseUrl) + if err != nil { + return nil, err + } + keyVaultID, err := keyVaultParse.KeyVaultID(*keyVaultIDRaw) + if err != nil { + return nil, err + } + return utils.String(fmt.Sprintf("%s_%s_%s", keyVaultID.Name, keyVaultKeyID.Name, keyVaultKeyID.Version)), nil +} + +func resourceArmMySQLServerKeyCreateUpdate(d *schema.ResourceData, meta interface{}) error { + keysClient := meta.(*clients.Client).MySQL.ServerKeysClient + vaultsClient := meta.(*clients.Client).KeyVault.VaultsClient + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + serverID, err := parse.MySQLServerID(d.Get("server_id").(string)) + if err != nil { + return err + } + keyVaultKeyURI := d.Get("key_vault_key_id").(string) + name, err := getMySQLServerKeyName(ctx, vaultsClient, keyVaultKeyURI) + if err != nil { + return fmt.Errorf("cannot compose name for MySQL Server Key (Resource Group %q / Server %q): %+v", serverID.ResourceGroup, serverID.Name, err) + } + + locks.ByName(serverID.Name, mySQLServerResourceName) + defer locks.UnlockByName(serverID.Name, mySQLServerResourceName) + + if d.IsNewResource() { + // This resource is a singleton, but its name can be anything. + // If you create a new key with different name with the old key, the service will not give you any warning but directly replace the old key with the new key. + // Therefore sometimes you cannot get the old key using the GET API since you may not know the name of the old key + resp, err := keysClient.List(ctx, serverID.ResourceGroup, serverID.Name) + if err != nil { + return fmt.Errorf("listing existing MySQL Server Keys in Resource Group %q / Server %q: %+v", serverID.ResourceGroup, serverID.Name, err) + } + keys := resp.Values() + if len(keys) > 1 { + return fmt.Errorf("expecting at most one MySQL Server Key, but got %q", len(keys)) + } + if len(keys) == 1 && keys[0].ID != nil && *keys[0].ID != "" { + return tf.ImportAsExistsError("azurerm_mysql_server_key", *keys[0].ID) + } + } + + param := mysql.ServerKey{ + ServerKeyProperties: &mysql.ServerKeyProperties{ + ServerKeyType: utils.String("AzureKeyVault"), + URI: &keyVaultKeyURI, + }, + } + + future, err := keysClient.CreateOrUpdate(ctx, serverID.Name, *name, param, serverID.ResourceGroup) + if err != nil { + return fmt.Errorf("creating/updating MySQL Server Key (Resource Group %q / Server %q): %+v", serverID.ResourceGroup, serverID.Name, err) + } + if err := future.WaitForCompletionRef(ctx, keysClient.Client); err != nil { + return fmt.Errorf("waiting for creation/update of MySQL Server Key (Resource Group %q / Server %q): %+v", serverID.ResourceGroup, serverID.Name, err) + } + + resp, err := keysClient.Get(ctx, serverID.ResourceGroup, serverID.Name, *name) + if err != nil { + return fmt.Errorf("retrieving MySQL Server Key (Resource Group %q / Server %q): %+v", serverID.ResourceGroup, serverID.Name, err) + } + if resp.ID == nil || *resp.ID == "" { + return fmt.Errorf("empty or nil ID returned for MySQL Server Key (Resource Group %q / Server %q): %+v", serverID.ResourceGroup, serverID.Name, err) + } + + d.SetId(*resp.ID) + + return resourceArmMySQLServerKeyRead(d, meta) +} + +func resourceArmMySQLServerKeyRead(d *schema.ResourceData, meta interface{}) error { + serversClient := meta.(*clients.Client).MySQL.ServersClient + keysClient := meta.(*clients.Client).MySQL.ServerKeysClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.MySQLServerKeyID(d.Id()) + if err != nil { + return err + } + + resp, err := keysClient.Get(ctx, id.ResourceGroup, id.ServerName, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[WARN] MySQL Server Key %q was not found (Resource Group %q / Server %q)", id.Name, id.ResourceGroup, id.ServerName) + d.SetId("") + return nil + } + + return fmt.Errorf("retrieving MySQL Server Key %q (Resource Group %q / Server %q): %+v", id.Name, id.ResourceGroup, id.ServerName, err) + } + + respServer, err := serversClient.Get(ctx, id.ResourceGroup, id.ServerName) + if err != nil { + return fmt.Errorf("cannot get MySQL Server ID: %+v", err) + } + + d.Set("server_id", respServer.ID) + if props := resp.ServerKeyProperties; props != nil { + d.Set("key_vault_key_id", props.URI) + } + + return nil +} + +func resourceArmMySQLServerKeyDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).MySQL.ServerKeysClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.MySQLServerKeyID(d.Id()) + if err != nil { + return err + } + + locks.ByName(id.ServerName, mySQLServerResourceName) + defer locks.UnlockByName(id.ServerName, mySQLServerResourceName) + + future, err := client.Delete(ctx, id.ServerName, id.Name, id.ResourceGroup) + if err != nil { + return fmt.Errorf("deleting MySQL Server Key %q (Resource Group %q / Server %q): %+v", id.Name, id.ResourceGroup, id.ServerName, err) + } + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for deletion of MySQL Server Key %q (Resource Group %q / Server %q): %+v", id.Name, id.ResourceGroup, id.ServerName, err) + } + + return nil +} diff --git a/azurerm/internal/services/mysql/mysql_server_resource.go b/azurerm/internal/services/mysql/mysql_server_resource.go index 47f8bdfd45d5..84342914b594 100644 --- a/azurerm/internal/services/mysql/mysql_server_resource.go +++ b/azurerm/internal/services/mysql/mysql_server_resource.go @@ -23,6 +23,10 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) +const ( + mySQLServerResourceName = "azurerm_mysql_server" +) + func resourceArmMySqlServer() *schema.Resource { return &schema.Resource{ Create: resourceArmMySqlServerCreate, @@ -32,7 +36,7 @@ func resourceArmMySqlServer() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - if _, err := parse.MysqlServerServerID(d.Id()); err != nil { + if _, err := parse.MySQLServerID(d.Id()); err != nil { return []*schema.ResourceData{d}, err } @@ -57,7 +61,7 @@ func resourceArmMySqlServer() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.MysqlServerServerName, + ValidateFunc: validate.MySQLServerName, }, "administrator_login": { @@ -103,7 +107,7 @@ func resourceArmMySqlServer() *schema.Resource { "creation_source_server_id": { Type: schema.TypeString, Optional: true, - ValidateFunc: validate.MysqlServerServerID, + ValidateFunc: validate.MySQLServerID, }, "fqdn": { @@ -571,7 +575,7 @@ func resourceArmMySqlServerUpdate(d *schema.ResourceData, meta interface{}) erro log.Printf("[INFO] preparing arguments for AzureRM MySQL Server update.") - id, err := parse.MysqlServerServerID(d.Id()) + id, err := parse.MySQLServerID(d.Id()) if err != nil { return fmt.Errorf("parsing MySQL Server ID : %v", err) } @@ -650,7 +654,7 @@ func resourceArmMySqlServerRead(d *schema.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.MysqlServerServerID(d.Id()) + id, err := parse.MySQLServerID(d.Id()) if err != nil { return fmt.Errorf("parsing MySQL Server ID : %v", err) } @@ -730,7 +734,7 @@ func resourceArmMySqlServerDelete(d *schema.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.MysqlServerServerID(d.Id()) + id, err := parse.MySQLServerID(d.Id()) if err != nil { return fmt.Errorf("parsing MySQL Server ID : %v", err) } diff --git a/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go b/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go index 87b01ef9e652..274145e2491c 100644 --- a/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go +++ b/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go @@ -50,7 +50,7 @@ func resourceArmMySQLVirtualNetworkRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.MysqlServerServerName, + ValidateFunc: validate.MySQLServerName, }, "subnet_id": { diff --git a/azurerm/internal/services/mysql/parse/mysql.go b/azurerm/internal/services/mysql/parse/mysql_server.go similarity index 79% rename from azurerm/internal/services/mysql/parse/mysql.go rename to azurerm/internal/services/mysql/parse/mysql_server.go index a8a370133682..d1d14f12a25e 100644 --- a/azurerm/internal/services/mysql/parse/mysql.go +++ b/azurerm/internal/services/mysql/parse/mysql_server.go @@ -6,18 +6,18 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" ) -type MysqlServerServerId struct { +type MySQLServerId struct { ResourceGroup string Name string } -func MysqlServerServerID(input string) (*MysqlServerServerId, error) { +func MySQLServerID(input string) (*MySQLServerId, error) { id, err := azure.ParseAzureResourceID(input) if err != nil { return nil, fmt.Errorf("[ERROR] Unable to parse MySQL Server ID %q: %+v", input, err) } - server := MysqlServerServerId{ + server := MySQLServerId{ ResourceGroup: id.ResourceGroup, } diff --git a/azurerm/internal/services/mysql/parse/mysql_server_key.go b/azurerm/internal/services/mysql/parse/mysql_server_key.go new file mode 100644 index 000000000000..70f76b7ece8f --- /dev/null +++ b/azurerm/internal/services/mysql/parse/mysql_server_key.go @@ -0,0 +1,37 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type MySQLServerKeyId struct { + ResourceGroup string + ServerName string + Name string +} + +func MySQLServerKeyID(input string) (*MySQLServerKeyId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("unable to parse MySQL Server Key ID %q: %+v", input, err) + } + + key := MySQLServerKeyId{ + ResourceGroup: id.ResourceGroup, + } + + if key.ServerName, err = id.PopSegment("servers"); err != nil { + return nil, err + } + if key.Name, err = id.PopSegment("keys"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &key, nil +} diff --git a/azurerm/internal/services/mysql/parse/mysql_server_key_test.go b/azurerm/internal/services/mysql/parse/mysql_server_key_test.go new file mode 100644 index 000000000000..976fb53f3ad0 --- /dev/null +++ b/azurerm/internal/services/mysql/parse/mysql_server_key_test.go @@ -0,0 +1,81 @@ +package parse + +import "testing" + +func TestMySQLServerKeyID(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *MySQLServerKeyId + }{ + { + Name: "Empty resource ID", + Input: "", + Expected: nil, + }, + { + Name: "No resourceGroups segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No resource group name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource group", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/", + Expected: nil, + }, + { + Name: "Missing server name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/", + Expected: nil, + }, + { + Name: "MySQL Server ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/test-mysql/", + Expected: nil, + }, + { + Name: "Missing key name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/test-mysql/keys/", + Expected: nil, + }, + { + Name: "Valid", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/test-mysql/keys/key1", + Expected: &MySQLServerKeyId{ + Name: "key1", + ResourceGroup: "test-rg", + ServerName: "test-mysql", + }, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := MySQLServerKeyID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ServerName != v.Expected.ServerName { + t.Fatalf("Expected %q but got %q for ServerName", v.Expected.ServerName, actual.ServerName) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} diff --git a/azurerm/internal/services/mysql/parse/mysql_test.go b/azurerm/internal/services/mysql/parse/mysql_server_test.go similarity index 90% rename from azurerm/internal/services/mysql/parse/mysql_test.go rename to azurerm/internal/services/mysql/parse/mysql_server_test.go index c3ccf38972ea..c01099bf2ba4 100644 --- a/azurerm/internal/services/mysql/parse/mysql_test.go +++ b/azurerm/internal/services/mysql/parse/mysql_server_test.go @@ -4,11 +4,11 @@ import ( "testing" ) -func TestValidateMysqlServerServerID(t *testing.T) { +func TestMySQLServerID(t *testing.T) { testData := []struct { Name string Input string - Expected *MysqlServerServerId + Expected *MySQLServerId }{ { Name: "Empty resource ID", @@ -38,7 +38,7 @@ func TestValidateMysqlServerServerID(t *testing.T) { { Name: "Valid", Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/test-mysql", - Expected: &MysqlServerServerId{ + Expected: &MySQLServerId{ Name: "test-mysql", ResourceGroup: "test-rg", }, @@ -48,7 +48,7 @@ func TestValidateMysqlServerServerID(t *testing.T) { for _, v := range testData { t.Logf("[DEBUG] Testing %q", v.Name) - actual, err := MysqlServerServerID(v.Input) + actual, err := MySQLServerID(v.Input) if err != nil { if v.Expected == nil { continue diff --git a/azurerm/internal/services/mysql/registration.go b/azurerm/internal/services/mysql/registration.go index 84b2fe79a129..0a5e9cd7762a 100644 --- a/azurerm/internal/services/mysql/registration.go +++ b/azurerm/internal/services/mysql/registration.go @@ -30,6 +30,7 @@ func (r Registration) SupportedResources() map[string]*schema.Resource { "azurerm_mysql_database": resourceArmMySqlDatabase(), "azurerm_mysql_firewall_rule": resourceArmMySqlFirewallRule(), "azurerm_mysql_server": resourceArmMySqlServer(), + "azurerm_mysql_server_key": resourceArmMySQLServerKey(), "azurerm_mysql_virtual_network_rule": resourceArmMySQLVirtualNetworkRule(), "azurerm_mysql_active_directory_administrator": resourceArmMySQLAdministrator()} } diff --git a/azurerm/internal/services/mysql/tests/mysql_server_key_resource_test.go b/azurerm/internal/services/mysql/tests/mysql_server_key_resource_test.go new file mode 100644 index 000000000000..584dbf7acb4c --- /dev/null +++ b/azurerm/internal/services/mysql/tests/mysql_server_key_resource_test.go @@ -0,0 +1,251 @@ +package tests + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMMySQLServerKey_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mysql_server_key", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMySQLServerKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMySQLServerKey_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerKeyExists(data.ResourceName), + ), + }, + }, + }) +} + +func TestAccAzureRMMySQLServerKey_updateKey(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mysql_server_key", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMySQLServerKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMySQLServerKey_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerKeyExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMySQLServerKey_updated(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerKeyExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMMySQLServerKey_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mysql_server_key", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMySQLServerKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMySQLServerKey_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerKeyExists(data.ResourceName), + ), + }, + data.RequiresImportErrorStep(testAccAzureRMMySQLServerKey_requiresImport), + }, + }) +} + +func testCheckAzureRMMySQLServerKeyDestroy(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).MySQL.ServerKeysClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_mysql_server_key" { + continue + } + + id, err := parse.MySQLServerKeyID(rs.Primary.ID) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.ServerName, id.Name) + if err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("retrieving MySQL Server Key: %+v", err) + } + return nil + } + + return fmt.Errorf("MySQL Server Key still exists:\n%#v", resp) + } + + return nil +} + +func testCheckAzureRMMySQLServerKeyExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).MySQL.ServerKeysClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + id, err := parse.MySQLServerKeyID(rs.Primary.ID) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.ServerName, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: MySQL Server Key %q (Resource Group %q / Server %q) does not exist", id.Name, id.ResourceGroup, id.ServerName) + } + return fmt.Errorf("Bad: Get on MySQLServerKeysClient: %+v", err) + } + + return nil + } +} + +func testAccAzureRMMySQLServerKey_template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features { + key_vault { + purge_soft_delete_on_destroy = false + } + } +} + +data "azurerm_client_config" "current" {} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_key_vault" "test" { + name = "acctestkv%s" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "standard" + soft_delete_enabled = true + purge_protection_enabled = true +} + +resource "azurerm_key_vault_access_policy" "server" { + key_vault_id = azurerm_key_vault.test.id + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = azurerm_mysql_server.test.identity.0.principal_id + key_permissions = ["get", "unwrapkey", "wrapkey"] + secret_permissions = ["get"] +} + +resource "azurerm_key_vault_access_policy" "client" { + key_vault_id = azurerm_key_vault.test.id + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + key_permissions = ["get", "create", "delete", "list", "restore", "recover", "unwrapkey", "wrapkey", "purge", "encrypt", "decrypt", "sign", "verify"] + secret_permissions = ["get"] +} + +resource "azurerm_key_vault_key" "first" { + name = "first" + key_vault_id = azurerm_key_vault.test.id + key_type = "RSA" + key_size = 2048 + key_opts = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"] + depends_on = [ + azurerm_key_vault_access_policy.client, + azurerm_key_vault_access_policy.server, + ] +} + +resource "azurerm_mysql_server" "test" { + name = "acctestmysqlsvr-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku_name = "GP_Gen5_2" + administrator_login = "acctestun" + administrator_login_password = "H@Sh1CoR3!" + ssl_enforcement_enabled = true + ssl_minimal_tls_version_enforced = "TLS1_1" + storage_mb = 51200 + version = "5.6" + + identity { + type = "SystemAssigned" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomInteger) +} + +func testAccAzureRMMySQLServerKey_basic(data acceptance.TestData) string { + template := testAccAzureRMMySQLServerKey_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mysql_server_key" "test" { + server_id = azurerm_mysql_server.test.id + key_vault_key_id = azurerm_key_vault_key.first.id +} +`, template) +} + +func testAccAzureRMMySQLServerKey_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMMySQLServerKey_basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mysql_server_key" "import" { + server_id = azurerm_mysql_server_key.test.server_id + key_vault_key_id = azurerm_mysql_server_key.test.key_vault_key_id +} +`, template) +} + +func testAccAzureRMMySQLServerKey_updated(data acceptance.TestData) string { + template := testAccAzureRMMySQLServerKey_template(data) + return fmt.Sprintf(` +%s +resource "azurerm_key_vault_key" "second" { + name = "second" + key_vault_id = azurerm_key_vault.test.id + key_type = "RSA" + key_size = 2048 + key_opts = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"] + depends_on = [ + azurerm_key_vault_access_policy.client, + azurerm_key_vault_access_policy.server, + ] +} +resource "azurerm_mysql_server_key" "test" { + server_id = azurerm_mysql_server.test.id + key_vault_key_id = azurerm_key_vault_key.second.id +} +`, template) +} diff --git a/azurerm/internal/services/mysql/validate/mysql.go b/azurerm/internal/services/mysql/validate/mysql_server.go similarity index 78% rename from azurerm/internal/services/mysql/validate/mysql.go rename to azurerm/internal/services/mysql/validate/mysql_server.go index e5abee8309ba..fb9579230a66 100644 --- a/azurerm/internal/services/mysql/validate/mysql.go +++ b/azurerm/internal/services/mysql/validate/mysql_server.go @@ -7,21 +7,21 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/parse" ) -func MysqlServerServerID(i interface{}, k string) (warnings []string, errors []error) { +func MySQLServerID(i interface{}, k string) (warnings []string, errors []error) { v, ok := i.(string) if !ok { errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) return warnings, errors } - if _, err := parse.MysqlServerServerID(v); err != nil { + if _, err := parse.MySQLServerID(v); err != nil { errors = append(errors, fmt.Errorf("Can not parse %q as a MySQL Server resource id: %v", k, err)) } return warnings, errors } -func MysqlServerServerName(i interface{}, k string) (_ []string, errors []error) { +func MySQLServerName(i interface{}, k string) (_ []string, errors []error) { if m, regexErrs := validate.RegExHelper(i, k, `^[0-9a-z][-0-9a-z]{1,61}[0-9a-z]$`); !m { return nil, append(regexErrs, fmt.Errorf("%q can contain only lowercase letters, numbers, and '-', but can't start or end with '-', and must be at least 3 characters and no more than 63 characters long.", k)) } diff --git a/azurerm/internal/services/mysql/validate/mysql_test.go b/azurerm/internal/services/mysql/validate/mysql_server_test.go similarity index 94% rename from azurerm/internal/services/mysql/validate/mysql_test.go rename to azurerm/internal/services/mysql/validate/mysql_server_test.go index 3e919164fb37..4c198d842b85 100644 --- a/azurerm/internal/services/mysql/validate/mysql_test.go +++ b/azurerm/internal/services/mysql/validate/mysql_server_test.go @@ -29,7 +29,7 @@ func TestValidateMysqlServerServerID(t *testing.T) { for _, v := range testData { t.Logf("[DEBUG] Testing %q..", v.input) - _, errors := MysqlServerServerID(v.input, "name") + _, errors := MySQLServerID(v.input, "name") actual := len(errors) == 0 if v.expected != actual { t.Fatalf("Expected %t but got %t", v.expected, actual) @@ -97,7 +97,7 @@ func TestValidateMysqlServerServerName(t *testing.T) { for _, v := range testData { t.Logf("[DEBUG] Testing %q..", v.input) - _, errors := MysqlServerServerName(v.input, "name") + _, errors := MySQLServerName(v.input, "name") actual := len(errors) == 0 if v.expected != actual { t.Fatalf("Expected %t but got %t", v.expected, actual) diff --git a/website/docs/r/mysql_server_key.html.markdown b/website/docs/r/mysql_server_key.html.markdown new file mode 100644 index 000000000000..eda4c1de8a8c --- /dev/null +++ b/website/docs/r/mysql_server_key.html.markdown @@ -0,0 +1,115 @@ +--- +subcategory: "Database" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_mysql_server_key" +description: |- + Manages a MySQL Server Key. +--- + +# azurerm_mysql_server_key + +Manages a Customer Managed Key for a MySQL Server. + +## Example Usage + +```hcl +data "azurerm_client_config" "current" {} + +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_key_vault" "example" { + name = "examplekv" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "premium" + soft_delete_enabled = true + purge_protection_enabled = true +} + +resource "azurerm_key_vault_access_policy" "server" { + key_vault_id = azurerm_key_vault.example.id + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = azurerm_mysql_server.example.identity.0.principal_id + key_permissions = ["get", "unwrapkey", "wrapkey"] + secret_permissions = ["get"] +} + +resource "azurerm_key_vault_access_policy" "client" { + key_vault_id = azurerm_key_vault.example.id + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + key_permissions = ["get", "create", "delete", "list", "restore", "recover", "unwrapkey", "wrapkey", "purge", "encrypt", "decrypt", "sign", "verify"] + secret_permissions = ["get"] +} + +resource "azurerm_key_vault_key" "example" { + name = "tfex-key" + key_vault_id = azurerm_key_vault.example.id + key_type = "RSA" + key_size = 2048 + key_opts = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"] + depends_on = [ + azurerm_key_vault_access_policy.client, + azurerm_key_vault_access_policy.server, + ] +} + +resource "azurerm_mysql_server" "example" { + name = "example-mysql-server" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + sku_name = "GP_Gen5_2" + administrator_login = "acctestun" + administrator_login_password = "H@Sh1CoR3!" + ssl_enforcement_enabled = true + ssl_minimal_tls_version_enforced = "TLS1_1" + storage_mb = 51200 + version = "5.6" + + identity { + type = "SystemAssigned" + } +} + +resource "azurerm_mysql_server_key" "example" { + server_id = azurerm_mysql_server.example.id + key_vault_key_id = azurerm_key_vault_key.example.id +} +``` + +## Argument Reference + +The following arguments are supported: + +* `server_id` - (Required) The ID of the MySQL Server. Changing this forces a new resource to be created. + +* `key_vault_key_id` - (Required) The URL to a Key Vault Key. + +## Attributes Reference + +The following attributes are exported in addition to the arguments listed above: + +* `id` - The ID of the MySQL Server Key. + +--- + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the MySQL Server Key. +* `update` - (Defaults to 30 minutes) Used when updating the MySQL Server Key. +* `read` - (Defaults to 5 minutes) Used when retrieving the MySQL Server Key. +* `delete` - (Defaults to 30 minutes) Used when deleting the MySQL Server Key. + +## Import + +A MySQL Server Key can be imported using the `resource id` of the MySQL Server Key, e.g. + +```shell +terraform import azurerm_mysql_server_key.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.DBforMySQL/servers/server1/keys/keyvaultname_key-name_keyversion +```