Skip to content

Commit

Permalink
Merge pull request #3141 from terraform-providers/f/api-management-ce…
Browse files Browse the repository at this point in the history
…rtificates

New Resource: `azurerm_api_management_certificate`
  • Loading branch information
tombuildsstuff authored Mar 29, 2019
2 parents 58fd636 + 60762d6 commit dc5976e
Show file tree
Hide file tree
Showing 6 changed files with 424 additions and 0 deletions.
5 changes: 5 additions & 0 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ type ArmClient struct {
// API Management
apiManagementApiClient apimanagement.APIClient
apiManagementApiOperationsClient apimanagement.APIOperationClient
apiManagementCertificatesClient apimanagement.CertificateClient
apiManagementGroupClient apimanagement.GroupClient
apiManagementGroupUsersClient apimanagement.GroupUserClient
apiManagementLoggerClient apimanagement.LoggerClient
Expand Down Expand Up @@ -508,6 +509,10 @@ func (c *ArmClient) registerApiManagementServiceClients(endpoint, subscriptionId
c.configureClient(&apiOperationsClient.Client, auth)
c.apiManagementApiOperationsClient = apiOperationsClient

certificatesClient := apimanagement.NewCertificateClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&certificatesClient.Client, auth)
c.apiManagementCertificatesClient = certificatesClient

groupsClient := apimanagement.NewGroupClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&groupsClient.Client, auth)
c.apiManagementGroupClient = groupsClient
Expand Down
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_api_management": resourceArmApiManagementService(),
"azurerm_api_management_api": resourceArmApiManagementApi(),
"azurerm_api_management_api_operation": resourceArmApiManagementApiOperation(),
"azurerm_api_management_certificate": resourceArmApiManagementCertificate(),
"azurerm_api_management_group": resourceArmApiManagementGroup(),
"azurerm_api_management_group_user": resourceArmApiManagementGroupUser(),
"azurerm_api_management_logger": resourceArmApiManagementLogger(),
Expand Down
170 changes: 170 additions & 0 deletions azurerm/resource_arm_api_management_certificate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package azurerm

import (
"fmt"
"log"
"time"

"github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2018-01-01/apimanagement"
"github.com/hashicorp/terraform/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/utils"
)

func resourceArmApiManagementCertificate() *schema.Resource {
return &schema.Resource{
Create: resourceArmApiManagementCertificateCreateUpdate,
Read: resourceArmApiManagementCertificateRead,
Update: resourceArmApiManagementCertificateCreateUpdate,
Delete: resourceArmApiManagementCertificateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": azure.SchemaApiManagementChildName(),

"resource_group_name": resourceGroupNameSchema(),

"api_management_name": azure.SchemaApiManagementName(),

"data": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
ValidateFunc: validate.Base64String(),
},

"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},

"expiration": {
Type: schema.TypeString,
Computed: true,
},

"subject": {
Type: schema.TypeString,
Computed: true,
},

"thumbprint": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func resourceArmApiManagementCertificateCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).apiManagementCertificatesClient
ctx := meta.(*ArmClient).StopContext

name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
serviceName := d.Get("api_management_name").(string)
data := d.Get("data").(string)
password := d.Get("password").(string)

if requireResourcesToBeImported {
existing, err := client.Get(ctx, resourceGroup, serviceName, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing Certificate %q (API Management Service %q / Resource Group %q): %s", name, serviceName, resourceGroup, err)
}
}

if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_api_management_certificate", *existing.ID)
}
}

parameters := apimanagement.CertificateCreateOrUpdateParameters{
CertificateCreateOrUpdateProperties: &apimanagement.CertificateCreateOrUpdateProperties{
Data: utils.String(data),
Password: utils.String(password),
},
}

if _, err := client.CreateOrUpdate(ctx, resourceGroup, serviceName, name, parameters, ""); err != nil {
return fmt.Errorf("Error creating or updating Certificate %q (Resource Group %q / API Management Service %q): %+v", name, resourceGroup, serviceName, err)
}

resp, err := client.Get(ctx, resourceGroup, serviceName, name)
if err != nil {
return fmt.Errorf("Error retrieving Certificate %q (Resource Group %q / API Management Service %q): %+v", name, resourceGroup, serviceName, err)
}
if resp.ID == nil {
return fmt.Errorf("Cannot read ID for Certificate %q (Resource Group %q / API Management Service %q)", name, resourceGroup, serviceName)
}
d.SetId(*resp.ID)

return resourceArmApiManagementCertificateRead(d, meta)
}

func resourceArmApiManagementCertificateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).apiManagementCertificatesClient
ctx := meta.(*ArmClient).StopContext

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
serviceName := id.Path["service"]
name := id.Path["certificates"]

resp, err := client.Get(ctx, resourceGroup, serviceName, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Certificate %q (Resource Group %q / API Management Service %q) was not found - removing from state!", name, resourceGroup, serviceName)
d.SetId("")
return nil
}

return fmt.Errorf("Error making Read request for Certificate %q (Resource Group %q / API Management Service %q): %+v", name, resourceGroup, serviceName, err)
}

d.Set("name", resp.Name)
d.Set("resource_group_name", resourceGroup)
d.Set("api_management_name", serviceName)

if props := resp.CertificateContractProperties; props != nil {

if expiration := props.ExpirationDate; expiration != nil {
formatted := expiration.Format(time.RFC3339)
d.Set("expiration", formatted)
}

d.Set("subject", props.Thumbprint)
d.Set("thumbprint", props.Thumbprint)
}

return nil
}

func resourceArmApiManagementCertificateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).apiManagementCertificatesClient
ctx := meta.(*ArmClient).StopContext

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
serviceName := id.Path["service"]
name := id.Path["certificates"]

if resp, err := client.Delete(ctx, resourceGroup, serviceName, name, ""); err != nil {
if !utils.ResponseWasNotFound(resp) {
return fmt.Errorf("Error deleting Certificate %q (Resource Group %q / API Management Service %q): %+v", name, resourceGroup, serviceName, err)
}
}

return nil
}
168 changes: 168 additions & 0 deletions azurerm/resource_arm_api_management_certificate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
package azurerm

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func TestAccAzureRMAPIManagementCertificate_basic(t *testing.T) {
resourceName := "azurerm_api_management_certificate.test"
ri := tf.AccRandTimeInt()
location := testLocation()

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMAPIManagementCertificateDestroy,
Steps: []resource.TestStep{
{
Config: testAccAzureRMAPIManagementCertificate_basic(ri, location),
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMAPIManagementCertificateExists(resourceName),
resource.TestCheckResourceAttrSet(resourceName, "expiration"),
resource.TestCheckResourceAttrSet(resourceName, "subject"),
resource.TestCheckResourceAttrSet(resourceName, "thumbprint"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{
// not returned from the API
"data",
"password",
},
},
},
})
}

func TestAccAzureRMAPIManagementCertificate_requiresImport(t *testing.T) {
if !requireResourcesToBeImported {
t.Skip("Skipping since resources aren't required to be imported")
return
}

resourceName := "azurerm_api_management_certificate.test"
ri := tf.AccRandTimeInt()
location := testLocation()

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMAPIManagementCertificateDestroy,
Steps: []resource.TestStep{
{
Config: testAccAzureRMAPIManagementCertificate_basic(ri, location),
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMAPIManagementCertificateExists(resourceName),
),
},
{
Config: testAccAzureRMAPIManagementCertificate_requiresImport(ri, location),
ExpectError: testRequiresImportError("azurerm_api_management_certificate"),
},
},
})
}

func testCheckAzureRMAPIManagementCertificateDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*ArmClient).apiManagementCertificatesClient
for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_api_management_certificate" {
continue
}

name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"]
serviceName := rs.Primary.Attributes["api_management_name"]

ctx := testAccProvider.Meta().(*ArmClient).StopContext
resp, err := client.Get(ctx, resourceGroup, serviceName, name)

if err != nil {
if !utils.ResponseWasNotFound(resp.Response) {
return err
}
}

return nil
}
return nil
}

func testCheckAzureRMAPIManagementCertificateExists(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)
}

name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"]
serviceName := rs.Primary.Attributes["api_management_name"]

client := testAccProvider.Meta().(*ArmClient).apiManagementCertificatesClient
ctx := testAccProvider.Meta().(*ArmClient).StopContext
resp, err := client.Get(ctx, resourceGroup, serviceName, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Bad: API Management Certificate %q (Resource Group %q / API Management Service %q) does not exist", name, resourceGroup, serviceName)
}
return fmt.Errorf("Bad: Get on apiManagementCertificatesClient: %+v", err)
}

return nil
}
}

func testAccAzureRMAPIManagementCertificate_basic(rInt int, location string) string {
return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
name = "acctestRG-%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"
capacity = 1
}
}
resource "azurerm_api_management_certificate" "test" {
name = "example-cert"
api_management_name = "${azurerm_api_management.test.name}"
resource_group_name = "${azurerm_resource_group.test.name}"
data = "${base64encode(file("testdata/keyvaultcert.pfx"))}"
password = ""
}
`, rInt, location, rInt)
}

func testAccAzureRMAPIManagementCertificate_requiresImport(rInt int, location string) string {
template := testAccAzureRMAPIManagementCertificate_basic(rInt, location)
return fmt.Sprintf(`
%s
resource "azurerm_api_management_certificate" "import" {
name = "${azurerm_api_management_certificate.test.name}"
api_management_name = "${azurerm_api_management_certificate.test.api_management_name}"
resource_group_name = "${azurerm_api_management_certificate.test.resource_group_name}"
data = "${azurerm_api_management_certificate.test.data}"
password = "${azurerm_api_management_certificate.test.password}"
}
`, template)
}
4 changes: 4 additions & 0 deletions website/azurerm.erb
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,10 @@
<a href="/docs/providers/azurerm/r/api_management_api_operation.html">azurerm_api_management_api_operation</a>
</li>

<li<%= sidebar_current("docs-azurerm-datasource-api-management-certificate") %>>
<a href="/docs/providers/azurerm/r/api_management_certificate.html">azurerm_api_management_certificate</a>
</li>

<li<%= sidebar_current("docs-azurerm-resource-api-management-group-x") %>>
<a href="/docs/providers/azurerm/r/api_management_group.html">azurerm_api_management_group</a>
</li>
Expand Down
Loading

0 comments on commit dc5976e

Please sign in to comment.