Skip to content

Commit

Permalink
Enhance - azurerm_api_management_api_schema support config `compone…
Browse files Browse the repository at this point in the history
…nts` and `definitions` (#18394)

Co-authored-by: xuzhang3 <Zhangxu894765>
  • Loading branch information
xuzhang3 authored Sep 15, 2022
1 parent cf51a7c commit 6fe7676
Show file tree
Hide file tree
Showing 6 changed files with 147 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,29 @@ func resourceApiManagementApiSchema() *pluginsdk.Resource {

"value": {
Type: pluginsdk.TypeString,
Required: true,
Optional: true,
ValidateFunc: validation.StringIsNotEmpty,
DiffSuppressFunc: func(k, old, new string, d *pluginsdk.ResourceData) bool {
if d.Get("content_type") == "application/vnd.ms-azure-apim.swagger.definitions+json" || d.Get("content_type") == "application/vnd.oai.openapi.components+json" {
return pluginsdk.SuppressJsonDiff(k, old, new, d)
}
return old == new
},
ExactlyOneOf: []string{"value", "definitions", "components"},
},

"components": {
Type: pluginsdk.TypeString,
Optional: true,
DiffSuppressFunc: pluginsdk.SuppressJsonDiff,
ExactlyOneOf: []string{"value", "definitions", "components"},
},

"definitions": {
Type: pluginsdk.TypeString,
Optional: true,
DiffSuppressFunc: pluginsdk.SuppressJsonDiff,
ExactlyOneOf: []string{"value", "definitions", "components"},
},
},
}
Expand Down Expand Up @@ -88,16 +103,25 @@ func resourceApiManagementApiSchemaCreateUpdate(d *pluginsdk.ResourceData, meta
}

contentType := d.Get("content_type").(string)
value := d.Get("value").(string)
parameters := apimanagement.SchemaContract{
SchemaContractProperties: &apimanagement.SchemaContractProperties{
ContentType: &contentType,
SchemaDocumentProperties: &apimanagement.SchemaDocumentProperties{
Value: &value,
},
ContentType: &contentType,
SchemaDocumentProperties: &apimanagement.SchemaDocumentProperties{},
},
}

if v, ok := d.GetOk("value"); ok {
parameters.SchemaContractProperties.SchemaDocumentProperties.Value = utils.String(v.(string))
}

if v, ok := d.GetOk("components"); ok {
parameters.SchemaContractProperties.SchemaDocumentProperties.Components = v.(string)
}

if v, ok := d.GetOk("definitions"); ok {
parameters.SchemaContractProperties.SchemaDocumentProperties.Definitions = v.(string)
}

future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.ServiceName, id.ApiName, id.SchemaName, parameters, "")
if err != nil {
return fmt.Errorf("creating/updating %s: %s", id, err)
Expand All @@ -120,6 +144,7 @@ func resourceApiManagementApiSchemaCreateUpdate(d *pluginsdk.ResourceData, meta
d.SetId(id.ID())
return nil
})

if err != nil {
return fmt.Errorf("getting %s: %+v", id, err)
}
Expand Down Expand Up @@ -155,31 +180,25 @@ func resourceApiManagementApiSchemaRead(d *pluginsdk.ResourceData, meta interfac
if properties := resp.SchemaContractProperties; properties != nil {
d.Set("content_type", properties.ContentType)
if documentProperties := properties.SchemaDocumentProperties; documentProperties != nil {
/*
As per https://docs.microsoft.com/en-us/rest/api/apimanagement/2019-12-01/api-schema/get#schemacontract
- Swagger Schema use application/vnd.ms-azure-apim.swagger.definitions+json
- WSDL Schema use application/vnd.ms-azure-apim.xsd+xml
- OpenApi Schema use application/vnd.oai.openapi.components+json
- WADL Schema use application/vnd.ms-azure-apim.wadl.grammars+xml.
Definitions used for Swagger/OpenAPI schemas only, otherwise Value is used
*/
switch *properties.ContentType {
case "application/vnd.ms-azure-apim.swagger.definitions+json", "application/vnd.oai.openapi.components+json":
if documentProperties.Definitions != nil {
value, err := json.Marshal(documentProperties.Definitions)
if err != nil {
return fmt.Errorf("[FATAL] Unable to serialize schema to json. Error: %+v. Schema struct: %+v", err, documentProperties.Definitions)
}
d.Set("value", string(value))
}
case "application/vnd.ms-azure-apim.xsd+xml", "application/vnd.ms-azure-apim.wadl.grammars+xml":
d.Set("value", documentProperties.Value)
default:
log.Printf("[WARN] Unknown content type %q for %s", *properties.ContentType, *id)
if documentProperties.Value != nil {
d.Set("value", documentProperties.Value)
}

if properties.Components != nil {
value, err := convert2Str(properties.Components)
if err != nil {
return err
}
d.Set("components", value)
}

if properties.Definitions != nil {
value, err := convert2Str(properties.Definitions)
if err != nil {
return err
}
d.Set("definitions", value)
}
}
}
return nil
Expand All @@ -203,3 +222,17 @@ func resourceApiManagementApiSchemaDelete(d *pluginsdk.ResourceData, meta interf

return nil
}

func convert2Str(rawVal interface{}) (string, error) {
value := ""
if val, ok := rawVal.(string); ok {
value = val
} else {
val, err := json.Marshal(rawVal)
if err != nil {
return "", fmt.Errorf("failed to marshal to json: %+v", err)
}
value = string(val)
}
return value, nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"os"
"strings"
"testing"

"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
Expand Down Expand Up @@ -37,14 +36,13 @@ func TestAccApiManagementApiSchema_basic(t *testing.T) {
func TestAccApiManagementApiSchema_basicSwagger(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_api_management_api_schema", "test")
r := ApiManagementApiSchemaResource{}
schema, _ := os.ReadFile("testdata/api_management_api_schema_swagger.json")

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basicSwagger(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
check.That(data.ResourceName).Key("value").HasValue(strings.TrimRight(string(schema), "\r\n")),
check.That(data.ResourceName).Key("value").Exists(),
),
},
data.ImportStep(),
Expand All @@ -66,6 +64,37 @@ func TestAccApiManagementApiSchema_requiresImport(t *testing.T) {
})
}

func TestAccApiManagementApiSchema_components(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_api_management_api_schema", "test")
r := ApiManagementApiSchemaResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.components(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
check.That(data.ResourceName).Key("components").Exists(),
),
},
data.ImportStep(),
})
}

func TestAccApiManagementApiSchema_definitions(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_api_management_api_schema", "test")
r := ApiManagementApiSchemaResource{}

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

func (ApiManagementApiSchemaResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := parse.ApiSchemaID(state.ID)
if err != nil {
Expand Down Expand Up @@ -104,7 +133,7 @@ resource "azurerm_api_management_api_schema" "test" {
api_management_name = azurerm_api_management_api.test.api_management_name
resource_group_name = azurerm_api_management_api.test.resource_group_name
schema_id = "acctestSchema%d"
content_type = "application/vnd.ms-azure-apim.swagger.definitions+json"
content_type = "application/json"
value = file("testdata/api_management_api_schema_swagger.json")
}
`, r.template(data), data.RandomInteger)
Expand Down Expand Up @@ -156,3 +185,47 @@ resource "azurerm_api_management_api" "test" {
}
`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger)
}

func (r ApiManagementApiSchemaResource) components(data acceptance.TestData) string {
return fmt.Sprintf(`
%s
resource "azurerm_api_management_api_schema" "test" {
api_name = azurerm_api_management_api.test.name
api_management_name = azurerm_api_management_api.test.api_management_name
resource_group_name = azurerm_api_management_api.test.resource_group_name
schema_id = "acctestSchema%d"
content_type = "application/vnd.oai.openapi.components+json"
components = file("testdata/api_management_api_schema_swagger.json")
}
`, r.template(data), data.RandomInteger)
}

func (r ApiManagementApiSchemaResource) definitionsJson(data acceptance.TestData) string {
return fmt.Sprintf(`
%s
resource "azurerm_api_management_api_schema" "test" {
api_name = azurerm_api_management_api.test.name
api_management_name = azurerm_api_management_api.test.api_management_name
resource_group_name = azurerm_api_management_api.test.resource_group_name
schema_id = "acctestSchema%d"
content_type = "application/vnd.ms-azure-apim.swagger.definitions+json"
definitions = file("testdata/api_management_api_swagger_definitions.json")
}
`, r.template(data), data.RandomInteger)
}
func (r ApiManagementApiSchemaResource) definitionsYaml(data acceptance.TestData) string {
return fmt.Sprintf(`
%s
resource "azurerm_api_management_api_schema" "test" {
api_name = azurerm_api_management_api.test.name
api_management_name = azurerm_api_management_api.test.api_management_name
resource_group_name = azurerm_api_management_api.test.resource_group_name
schema_id = "acctestSchema%d"
content_type = "application/vnd.ms-azure-apim.swagger.definitions+json"
definitions = file("testdata/api_management_api_swagger_definitions.yaml")
}
`, r.template(data), data.RandomInteger)
}
Loading

0 comments on commit 6fe7676

Please sign in to comment.