Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create azure App Service resource #2

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,11 @@ type ArmClient struct {
sqlServersClient sql.ServersClient

appServicePlansClient web.AppServicePlansClient
appsClient web.AppsClient

appInsightsClient appinsights.ComponentsClient

servicePrincipalsClient graphrbac.ServicePrincipalsClient

appsClient web.AppsClient
}

func withRequestLogging() autorest.SendDecorator {
Expand Down Expand Up @@ -575,6 +574,12 @@ func (c *Config) getArmClient() (*ArmClient, error) {
aspc.Sender = autorest.CreateSender(withRequestLogging())
client.appServicePlansClient = aspc

ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID)
setUserAgent(&ac.Client)
ac.Authorizer = auth
ac.Sender = autorest.CreateSender(withRequestLogging())
client.appsClient = ac

ai := appinsights.NewComponentsClientWithBaseURI(endpoint, c.SubscriptionID)
setUserAgent(&ai.Client)
ai.Authorizer = auth
Expand All @@ -587,12 +592,6 @@ func (c *Config) getArmClient() (*ArmClient, error) {
spc.Sender = autorest.CreateSender(withRequestLogging())
client.servicePrincipalsClient = spc

ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID)
setUserAgent(&ac.Client)
ac.Authorizer = auth
ac.Sender = autorest.CreateSender(withRequestLogging())
client.appsClient = ac

kvc := keyvault.NewVaultsClientWithBaseURI(endpoint, c.SubscriptionID)
setUserAgent(&kvc.Client)
kvc.Authorizer = auth
Expand Down
83 changes: 83 additions & 0 deletions azurerm/import_arm_app_service_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package azurerm

import (
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAzureRMAppService_importBasic(t *testing.T) {
resourceName := "azurerm_app_service.test"

ri := acctest.RandInt()
config := testAccAzureRMAppService_basic(ri, testLocation())

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMAppServiceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: config,
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_dns_registration", "skip_custom_domain_verification", "skip_dns_registration", "delete_metrics"},
},
},
})
}

func TestAccAzureRMAppService_importComplete(t *testing.T) {
resourceName := "azurerm_app_service.test"

ri := acctest.RandInt()
config := testAccAzureRMAppService_complete(ri, testLocation())

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMAppServiceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: config,
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_dns_registration", "skip_custom_domain_verification", "skip_dns_registration", "delete_metrics"},
},
},
})
}

func TestAccAzureRMAppService_importCompleteAlwaysOn(t *testing.T) {
resourceName := "azurerm_app_service.test"

ri := acctest.RandInt()
config := testAccAzureRMAppService_completeAlwaysOn(ri, testLocation())

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMAppServiceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: config,
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_dns_registration", "skip_custom_domain_verification", "skip_dns_registration", "delete_metrics"},
},
},
})
}
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ func Provider() terraform.ResourceProvider {
ResourcesMap: map[string]*schema.Resource{
"azurerm_application_insights": resourceArmApplicationInsights(),
"azurerm_app_service_plan": resourceArmAppServicePlan(),
"azurerm_app_service": resourceArmAppService(),
"azurerm_availability_set": resourceArmAvailabilitySet(),
"azurerm_cdn_endpoint": resourceArmCdnEndpoint(),
"azurerm_cdn_profile": resourceArmCdnProfile(),
Expand Down
223 changes: 223 additions & 0 deletions azurerm/resource_arm_app_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
package azurerm

import (
"fmt"
"log"
"net/http"
"strconv"

"github.com/Azure/azure-sdk-for-go/arm/web"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmAppService() *schema.Resource {
return &schema.Resource{
Create: resourceArmAppServiceCreateUpdate,
Read: resourceArmAppServiceRead,
Update: resourceArmAppServiceCreateUpdate,
Delete: resourceArmAppServiceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"resource_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"skip_dns_registration": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"skip_custom_domain_verification": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"force_dns_registration": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"ttl_in_seconds": {
Type: schema.TypeInt,
Optional: true,
},
"site_config": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_service_plan_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"always_on": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
},
},
"location": locationSchema(),
"tags": tagsSchema(),
"delete_metrics": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
}
}

func resourceArmAppServiceCreateUpdate(d *schema.ResourceData, meta interface{}) error {
appClient := meta.(*ArmClient).appsClient

log.Printf("[INFO] preparing arguments for Azure ARM App Service creation.")

resGroup := d.Get("resource_group_name").(string)
name := d.Get("name").(string)
skipDNSRegistration := d.Get("skip_dns_registration").(bool)
skipCustomDomainVerification := d.Get("skip_custom_domain_verification").(bool)
forceDNSRegistration := d.Get("force_dns_registration").(bool)
ttlInSeconds := 0
if v, ok := d.GetOk("ttl_in_seconds"); ok {
ttlInSeconds = v.(int)
}
location := d.Get("location").(string)
tags := d.Get("tags").(map[string]interface{})

siteProps := expandAzureRmAppServiceSiteProps(d)

siteEnvelope := web.Site{
Location: &location,
Tags: expandTags(tags),
SiteProperties: siteProps,
}

_, error := appClient.CreateOrUpdate(resGroup, name, siteEnvelope, &skipDNSRegistration, &skipCustomDomainVerification, &forceDNSRegistration, strconv.Itoa(ttlInSeconds), make(chan struct{}))
err := <-error
if err != nil {
return err
}

read, err := appClient.Get(resGroup, name)
if err != nil {
return err
}
if read.ID == nil {
return fmt.Errorf("Cannot read App Service %s (resource group %s) ID", name, resGroup)
}

d.SetId(*read.ID)

return resourceArmAppServiceRead(d, meta)
}

func resourceArmAppServiceRead(d *schema.ResourceData, meta interface{}) error {
appClient := meta.(*ArmClient).appsClient

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}

log.Printf("[DEBUG] Reading App Service details %s", id)

resGroup := id.ResourceGroup
name := id.Path["sites"]

resp, err := appClient.Get(resGroup, name)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on AzureRM App Service %s: %+v", name, err)
}

d.Set("name", name)
d.Set("resource_group_name", resGroup)
d.Set("location", azureRMNormalizeLocation(*resp.Location))

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we set the additional fields here?

if siteProps := resp.SiteProperties; siteProps != nil {
d.Set("site_config", flattenAzureRmAppServiceSiteProps(siteProps))
}

flattenAndSetTags(d, resp.Tags)

return nil
}

func resourceArmAppServiceDelete(d *schema.ResourceData, meta interface{}) error {
appClient := meta.(*ArmClient).appsClient

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["sites"]

log.Printf("[DEBUG] Deleting App Service %s: %s", resGroup, name)

deleteMetrics := d.Get("delete_metrics").(bool)
deleteEmptyServerFarm := true
skipDNSRegistration := d.Get("skip_dns_registration").(bool)

_, err = appClient.Delete(resGroup, name, &deleteMetrics, &deleteEmptyServerFarm, &skipDNSRegistration)

return err
}

func expandAzureRmAppServiceSiteProps(d *schema.ResourceData) *web.SiteProperties {
configs := d.Get("site_config").([]interface{})
siteProps := web.SiteProperties{}
if len(configs) == 0 {
return &siteProps
}
config := configs[0].(map[string]interface{})

siteConfig := web.SiteConfig{}
alwaysOn := config["always_on"].(bool)
siteConfig.AlwaysOn = utils.Bool(alwaysOn)

siteProps.SiteConfig = &siteConfig

serverFarmID := config["app_service_plan_id"].(string)
siteProps.ServerFarmID = &serverFarmID

return &siteProps
}

func flattenAzureRmAppServiceSiteProps(siteProps *web.SiteProperties) []interface{} {
result := make([]interface{}, 0, 1)
site_config := make(map[string]interface{}, 0)

if siteProps.ServerFarmID != nil {
site_config["app_service_plan_id"] = *siteProps.ServerFarmID
}

siteConfig := siteProps.SiteConfig
log.Printf("[DEBUG] SiteConfig is %s", siteConfig)
if siteConfig != nil {
if siteConfig.AlwaysOn != nil {
site_config["always_on"] = *siteConfig.AlwaysOn
}
}

result = append(result, site_config)
return result
}
Loading