diff --git a/azurerm/helpers/validate/google.go b/azurerm/helpers/validate/google.go new file mode 100644 index 000000000000..f861a143c149 --- /dev/null +++ b/azurerm/helpers/validate/google.go @@ -0,0 +1,14 @@ +package validate + +import ( + "fmt" + "regexp" +) + +func GoogleClientID(v interface{}, k string) (warnings []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[A-Za-z0-9-]+\.apps\.googleusercontent\.com$`).MatchString(value) { + errors = append(errors, fmt.Errorf("%s must start with an identifier containing alphanumeric characters and hyphens and end with '.apps.googleusercontent.com'", k)) + } + return warnings, errors +} diff --git a/azurerm/helpers/validate/google_test.go b/azurerm/helpers/validate/google_test.go new file mode 100644 index 000000000000..b6a8dcb67b32 --- /dev/null +++ b/azurerm/helpers/validate/google_test.go @@ -0,0 +1,41 @@ +package validate + +import ( + "testing" +) + +func TestGoogleClientID(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "", + ErrCount: 1, + }, + { + Value: "invalid client id", + ErrCount: 1, + }, + { + Value: "00000000-0000-0000-0000-000000000000", + ErrCount: 1, + }, + { + Value: "123456789000-abcd12ef34gh56ij78900klmnopqrst0.apps.googleusercontent.org", + ErrCount: 1, + }, + { + Value: "123456789000-abcd12ef34gh56ij78900klmnopqrst0.apps.googleusercontent.com", + ErrCount: 0, + }, + } + + for _, tc := range cases { + _, errors := GoogleClientID(tc.Value, "client_id") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the Google Client ID %s to trigger a validation error", tc.Value) + } + } +} diff --git a/azurerm/internal/services/apimanagement/registration.go b/azurerm/internal/services/apimanagement/registration.go index 03232eec7fdd..0367832cd539 100644 --- a/azurerm/internal/services/apimanagement/registration.go +++ b/azurerm/internal/services/apimanagement/registration.go @@ -25,28 +25,29 @@ func (r Registration) SupportedDataSources() map[string]*schema.Resource { // SupportedResources returns the supported Resources supported by this Service func (r Registration) SupportedResources() map[string]*schema.Resource { return map[string]*schema.Resource{ - "azurerm_api_management": resourceArmApiManagementService(), - "azurerm_api_management_api": resourceArmApiManagementApi(), - "azurerm_api_management_api_operation": resourceArmApiManagementApiOperation(), - "azurerm_api_management_api_operation_policy": resourceArmApiManagementApiOperationPolicy(), - "azurerm_api_management_api_policy": resourceArmApiManagementApiPolicy(), - "azurerm_api_management_api_schema": resourceArmApiManagementApiSchema(), - "azurerm_api_management_api_version_set": resourceArmApiManagementApiVersionSet(), - "azurerm_api_management_authorization_server": resourceArmApiManagementAuthorizationServer(), - "azurerm_api_management_backend": resourceArmApiManagementBackend(), - "azurerm_api_management_certificate": resourceArmApiManagementCertificate(), - "azurerm_api_management_diagnostic": resourceArmApiManagementDiagnostic(), - "azurerm_api_management_group": resourceArmApiManagementGroup(), - "azurerm_api_management_group_user": resourceArmApiManagementGroupUser(), - "azurerm_api_management_identity_provider_aad": resourceArmApiManagementIdentityProviderAAD(), - "azurerm_api_management_logger": resourceArmApiManagementLogger(), - "azurerm_api_management_openid_connect_provider": resourceArmApiManagementOpenIDConnectProvider(), - "azurerm_api_management_product": resourceArmApiManagementProduct(), - "azurerm_api_management_product_api": resourceArmApiManagementProductApi(), - "azurerm_api_management_product_group": resourceArmApiManagementProductGroup(), - "azurerm_api_management_product_policy": resourceArmApiManagementProductPolicy(), - "azurerm_api_management_property": resourceArmApiManagementProperty(), - "azurerm_api_management_subscription": resourceArmApiManagementSubscription(), - "azurerm_api_management_user": resourceArmApiManagementUser(), + "azurerm_api_management": resourceArmApiManagementService(), + "azurerm_api_management_api": resourceArmApiManagementApi(), + "azurerm_api_management_api_operation": resourceArmApiManagementApiOperation(), + "azurerm_api_management_api_operation_policy": resourceArmApiManagementApiOperationPolicy(), + "azurerm_api_management_api_policy": resourceArmApiManagementApiPolicy(), + "azurerm_api_management_api_schema": resourceArmApiManagementApiSchema(), + "azurerm_api_management_api_version_set": resourceArmApiManagementApiVersionSet(), + "azurerm_api_management_authorization_server": resourceArmApiManagementAuthorizationServer(), + "azurerm_api_management_backend": resourceArmApiManagementBackend(), + "azurerm_api_management_certificate": resourceArmApiManagementCertificate(), + "azurerm_api_management_diagnostic": resourceArmApiManagementDiagnostic(), + "azurerm_api_management_group": resourceArmApiManagementGroup(), + "azurerm_api_management_group_user": resourceArmApiManagementGroupUser(), + "azurerm_api_management_identity_provider_aad": resourceArmApiManagementIdentityProviderAAD(), + "azurerm_api_management_identity_provider_google": resourceArmApiManagementIdentityProviderGoogle(), + "azurerm_api_management_logger": resourceArmApiManagementLogger(), + "azurerm_api_management_openid_connect_provider": resourceArmApiManagementOpenIDConnectProvider(), + "azurerm_api_management_product": resourceArmApiManagementProduct(), + "azurerm_api_management_product_api": resourceArmApiManagementProductApi(), + "azurerm_api_management_product_group": resourceArmApiManagementProductGroup(), + "azurerm_api_management_product_policy": resourceArmApiManagementProductPolicy(), + "azurerm_api_management_property": resourceArmApiManagementProperty(), + "azurerm_api_management_subscription": resourceArmApiManagementSubscription(), + "azurerm_api_management_user": resourceArmApiManagementUser(), } } diff --git a/azurerm/internal/services/apimanagement/resource_arm_api_management_identity_provider_google.go b/azurerm/internal/services/apimanagement/resource_arm_api_management_identity_provider_google.go new file mode 100644 index 000000000000..4241bd2c2c42 --- /dev/null +++ b/azurerm/internal/services/apimanagement/resource_arm_api_management_identity_provider_google.go @@ -0,0 +1,159 @@ +package apimanagement + +import ( + "fmt" + "log" + "time" + + "github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2018-01-01/apimanagement" + "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/helpers/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmApiManagementIdentityProviderGoogle() *schema.Resource { + return &schema.Resource{ + Create: resourceArmApiManagementIdentityProviderGoogleCreateUpdate, + Read: resourceArmApiManagementIdentityProviderGoogleRead, + Update: resourceArmApiManagementIdentityProviderGoogleCreateUpdate, + Delete: resourceArmApiManagementIdentityProviderGoogleDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Read: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "resource_group_name": azure.SchemaResourceGroupName(), + + "api_management_name": azure.SchemaApiManagementName(), + + "client_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.GoogleClientID, + }, + + "client_secret": { + Type: schema.TypeString, + Required: true, + Sensitive: true, + ValidateFunc: validate.NoEmptyStrings, + }, + }, + } +} + +func resourceArmApiManagementIdentityProviderGoogleCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).ApiManagement.IdentityProviderClient + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + resourceGroup := d.Get("resource_group_name").(string) + serviceName := d.Get("api_management_name").(string) + clientID := d.Get("client_id").(string) + clientSecret := d.Get("client_secret").(string) + + if features.ShouldResourcesBeImported() && d.IsNewResource() { + existing, err := client.Get(ctx, resourceGroup, serviceName, apimanagement.Google) + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("Error checking for presence of existing Identity Provider %q (API Management Service %q / Resource Group %q): %s", apimanagement.Google, serviceName, resourceGroup, err) + } + } + + if existing.ID != nil && *existing.ID != "" { + return tf.ImportAsExistsError("azurerm_api_management_identity_provider_google", *existing.ID) + } + } + + parameters := apimanagement.IdentityProviderContract{ + IdentityProviderContractProperties: &apimanagement.IdentityProviderContractProperties{ + ClientID: utils.String(clientID), + ClientSecret: utils.String(clientSecret), + Type: apimanagement.Google, + }, + } + + if _, err := client.CreateOrUpdate(ctx, resourceGroup, serviceName, apimanagement.Google, parameters, ""); err != nil { + return fmt.Errorf("Error creating or updating Identity Provider %q (Resource Group %q / API Management Service %q): %+v", apimanagement.Google, resourceGroup, serviceName, err) + } + + resp, err := client.Get(ctx, resourceGroup, serviceName, apimanagement.Google) + if err != nil { + return fmt.Errorf("Error retrieving Identity Provider %q (Resource Group %q / API Management Service %q): %+v", apimanagement.Google, resourceGroup, serviceName, err) + } + if resp.ID == nil { + return fmt.Errorf("Cannot read ID for Identity Provider %q (Resource Group %q / API Management Service %q)", apimanagement.Google, resourceGroup, serviceName) + } + d.SetId(*resp.ID) + + return resourceArmApiManagementIdentityProviderGoogleRead(d, meta) +} + +func resourceArmApiManagementIdentityProviderGoogleRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).ApiManagement.IdentityProviderClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := azure.ParseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + serviceName := id.Path["service"] + identityProviderName := id.Path["identityProviders"] + + resp, err := client.Get(ctx, resourceGroup, serviceName, apimanagement.IdentityProviderType(identityProviderName)) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[DEBUG] Identity Provider %q (Resource Group %q / API Management Service %q) was not found - removing from state!", identityProviderName, resourceGroup, serviceName) + d.SetId("") + return nil + } + + return fmt.Errorf("Error making Read request for Identity Provider %q (Resource Group %q / API Management Service %q): %+v", identityProviderName, resourceGroup, serviceName, err) + } + + d.Set("resource_group_name", resourceGroup) + d.Set("api_management_name", serviceName) + + if props := resp.IdentityProviderContractProperties; props != nil { + d.Set("client_id", props.ClientID) + d.Set("client_secret", props.ClientSecret) + } + + return nil +} + +func resourceArmApiManagementIdentityProviderGoogleDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).ApiManagement.IdentityProviderClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := azure.ParseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + serviceName := id.Path["service"] + identityProviderName := id.Path["identityProviders"] + + if resp, err := client.Delete(ctx, resourceGroup, serviceName, apimanagement.IdentityProviderType(identityProviderName), ""); err != nil { + if !utils.ResponseWasNotFound(resp) { + return fmt.Errorf("Error deleting Identity Provider %q (Resource Group %q / API Management Service %q): %+v", identityProviderName, resourceGroup, serviceName, err) + } + } + + return nil +} diff --git a/azurerm/internal/services/apimanagement/tests/resource_arm_api_management_identity_provider_google_test.go b/azurerm/internal/services/apimanagement/tests/resource_arm_api_management_identity_provider_google_test.go new file mode 100644 index 000000000000..41347ca353fd --- /dev/null +++ b/azurerm/internal/services/apimanagement/tests/resource_arm_api_management_identity_provider_google_test.go @@ -0,0 +1,200 @@ +package tests + +import ( + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2018-01-01/apimanagement" + "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/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMApiManagementIdentityProviderGoogle_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management_identity_provider_google", "test") + config := testAccAzureRMApiManagementIdentityProviderGoogle_basic(data) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementIdentityProviderGoogleDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementIdentityProviderGoogleExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagementIdentityProviderGoogle_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management_identity_provider_google", "test") + config := testAccAzureRMApiManagementIdentityProviderGoogle_basic(data) + updateConfig := testAccAzureRMApiManagementIdentityProviderGoogle_update(data) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementIdentityProviderGoogleDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementIdentityProviderGoogleExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "client_id", "00000000.apps.googleusercontent.com"), + resource.TestCheckResourceAttr(data.ResourceName, "client_secret", "00000000000000000000000000000000"), + ), + }, + { + Config: updateConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementIdentityProviderGoogleExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "client_id", "11111111.apps.googleusercontent.com"), + resource.TestCheckResourceAttr(data.ResourceName, "client_secret", "11111111111111111111111111111111"), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagementIdentityProviderGoogle_requiresImport(t *testing.T) { + if !features.ShouldResourcesBeImported() { + t.Skip("Skipping since resources aren't required to be imported") + return + } + data := acceptance.BuildTestData(t, "azurerm_api_management_identity_provider_google", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementIdentityProviderGoogleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagementIdentityProviderGoogle_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementIdentityProviderGoogleExists(data.ResourceName), + ), + }, + data.RequiresImportErrorStep(testAccAzureRMApiManagementIdentityProviderGoogle_requiresImport), + }, + }) +} + +func testCheckAzureRMApiManagementIdentityProviderGoogleDestroy(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).ApiManagement.IdentityProviderClient + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_api_management_identity_provider_google" { + continue + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serviceName := rs.Primary.Attributes["api_management_name"] + + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + resp, err := client.Get(ctx, resourceGroup, serviceName, apimanagement.Google) + + if err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return err + } + } + + return nil + } + return nil +} + +func testCheckAzureRMApiManagementIdentityProviderGoogleExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serviceName := rs.Primary.Attributes["api_management_name"] + + client := acceptance.AzureProvider.Meta().(*clients.Client).ApiManagement.IdentityProviderClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + resp, err := client.Get(ctx, resourceGroup, serviceName, apimanagement.Google) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: API Management Identity Provider %q (Resource Group %q / API Management Service %q) does not exist", apimanagement.Google, resourceGroup, serviceName) + } + return fmt.Errorf("Bad: Get on apiManagementIdentityProviderClient: %+v", err) + } + + return nil + } +} + +func testAccAzureRMApiManagementIdentityProviderGoogle_basic(data acceptance.TestData) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-api-%d" + location = "%s" +} + +resource "azurerm_api_management" "test" { + name = "acctestAM-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + publisher_name = "pub1" + publisher_email = "pub1@email.com" + sku_name = "Developer_1" +} + +resource "azurerm_api_management_identity_provider_google" "test" { + resource_group_name = "${azurerm_resource_group.test.name}" + api_management_name = "${azurerm_api_management.test.name}" + client_id = "00000000.apps.googleusercontent.com" + client_secret = "00000000000000000000000000000000" +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + +func testAccAzureRMApiManagementIdentityProviderGoogle_update(data acceptance.TestData) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-api-%d" + location = "%s" +} + +resource "azurerm_api_management" "test" { + name = "acctestAM-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + publisher_name = "pub1" + publisher_email = "pub1@email.com" + sku_name = "Developer_1" +} + +resource "azurerm_api_management_identity_provider_google" "test" { + resource_group_name = "${azurerm_resource_group.test.name}" + api_management_name = "${azurerm_api_management.test.name}" + client_id = "11111111.apps.googleusercontent.com" + client_secret = "11111111111111111111111111111111" +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + +func testAccAzureRMApiManagementIdentityProviderGoogle_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMApiManagementIdentityProviderGoogle_basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_api_management_identity_provider_google" "import" { + resource_group_name = "${azurerm_api_management_identity_provider_google.test.resource_group_name}" + api_management_name = "${azurerm_api_management_identity_provider_google.test.api_management_name}" + client_id = "${azurerm_api_management_identity_provider_google.test.client_id}" + client_secret = "${azurerm_api_management_identity_provider_google.test.client_secret}" +} +`, template) +} diff --git a/website/docs/r/api_management_identity_provider_google.html.markdown b/website/docs/r/api_management_identity_provider_google.html.markdown new file mode 100644 index 000000000000..01534103f076 --- /dev/null +++ b/website/docs/r/api_management_identity_provider_google.html.markdown @@ -0,0 +1,65 @@ +--- +subcategory: "API Management" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_api_management_identity_provider_google" +sidebar_current: "docs-azurerm-resource-api-management-identity-provider-google" +description: |- + Manages an API Management Google Identity Provider. +--- + +# azurerm_api_management_identity_provider_google + +Manages an API Management Google Identity Provider. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_api_management" "example" { + name = "example-apim" + location = "${azurerm_resource_group.example.location}" + resource_group_name = "${azurerm_resource_group.example.name}" + publisher_name = "My Company" + publisher_email = "company@terraform.io" + sku_name = "Developer_1" +} + +resource "azurerm_api_management_identity_provider_google" "example" { + resource_group_name = "${azurerm_resource_group.example.name}" + api_management_name = "${azurerm_api_management.example.name}" + client_id = "00000000.apps.googleusercontent.com" + client_secret = "00000000000000000000000000000000" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `api_management_name` - (Required) The Name of the API Management Service where this Google Identity Provider should be created. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The Name of the Resource Group where the API Management Service exists. Changing this forces a new resource to be created. + +* `client_id` - (Required) Client Id for Google Sign-in. + +* `client_secret` - (Required) Client secret for Google Sign-in. + +--- + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The ID of the API Management Google Identity Provider. + +## Import + +API Management Google Identity Provider can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_api_management_identity_provider_google.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.ApiManagement/service/instance1/identityProviders/google +```