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

provider/azurerm: Adding azurerm_template_deployment resource #5758

Merged
merged 2 commits into from
Mar 21, 2016
Merged
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
8 changes: 8 additions & 0 deletions builtin/providers/azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ type ArmClient struct {

storageServiceClient storage.AccountsClient
storageUsageClient storage.UsageOperationsClient

deploymentsClient resources.DeploymentsClient
}

func withRequestLogging() autorest.SendDecorator {
Expand Down Expand Up @@ -295,6 +297,12 @@ func (c *Config) getArmClient() (*ArmClient, error) {
cec.Sender = autorest.CreateSender(withRequestLogging())
client.cdnEndpointsClient = cec

dc := resources.NewDeploymentsClient(c.SubscriptionID)
setUserAgent(&dc.Client)
dc.Authorizer = spt
dc.Sender = autorest.CreateSender(withRequestLogging())
client.deploymentsClient = dc

return &client, nil
}

Expand Down
3 changes: 2 additions & 1 deletion builtin/providers/azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_storage_container": resourceArmStorageContainer(),
"azurerm_storage_queue": resourceArmStorageQueue(),
"azurerm_subnet": resourceArmSubnet(),
"azurerm_template_deployment": resourceArmTemplateDeployment(),
"azurerm_virtual_machine": resourceArmVirtualMachine(),
"azurerm_virtual_network": resourceArmVirtualNetwork(),
},
Expand Down Expand Up @@ -143,7 +144,7 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {
func registerAzureResourceProvidersWithSubscription(config *Config, client *ArmClient) error {
providerClient := client.providers

providers := []string{"Microsoft.Network", "Microsoft.Compute", "Microsoft.Cdn", "Microsoft.Storage", "Microsoft.Sql", "Microsoft.Search"}
providers := []string{"Microsoft.Network", "Microsoft.Compute", "Microsoft.Cdn", "Microsoft.Storage", "Microsoft.Sql", "Microsoft.Search", "Microsoft.Resources"}

for _, v := range providers {
res, err := providerClient.Register(v)
Expand Down
213 changes: 213 additions & 0 deletions builtin/providers/azurerm/resource_arm_template_deployment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
package azurerm

import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"

"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceArmTemplateDeployment() *schema.Resource {
return &schema.Resource{
Create: resourceArmTemplateDeploymentCreate,
Read: resourceArmTemplateDeploymentRead,
Update: resourceArmTemplateDeploymentCreate,
Delete: resourceArmTemplateDeploymentDelete,

Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"resource_group_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"template_body": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
StateFunc: normalizeJson,
},

"parameters": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
},

"outputs": &schema.Schema{
Type: schema.TypeMap,
Computed: true,
},

"deployment_mode": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
}
}

func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient)
deployClient := client.deploymentsClient

name := d.Get("name").(string)
resGroup := d.Get("resource_group_name").(string)
deploymentMode := d.Get("deployment_mode").(string)

log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.")
properties := resources.DeploymentProperties{
Mode: resources.DeploymentMode(deploymentMode),
}

if v, ok := d.GetOk("parameters"); ok {
params := v.(map[string]interface{})

newParams := make(map[string]interface{}, len(params))
for key, val := range params {
newParams[key] = struct {
Value interface{}
}{
Value: val,
}
}

properties.Parameters = &newParams
}

if v, ok := d.GetOk("template_body"); ok {
template, err := expandTemplateBody(v.(string))
if err != nil {
return err
}

properties.Template = &template
}

deployment := resources.Deployment{
Properties: &properties,
}
resp, err := deployClient.CreateOrUpdate(resGroup, name, deployment)
if err != nil {
return nil
}

d.SetId(*resp.ID)

log.Printf("[DEBUG] Waiting for Template Deployment (%s) to become available", name)
stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "updating", "accepted", "running"},
Target: []string{"succeeded"},
Refresh: templateDeploymentStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Template Deployment (%s) to become available: %s", name, err)
}

return resourceArmTemplateDeploymentRead(d, meta)
}

func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient)
deployClient := client.deploymentsClient

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

resp, err := deployClient.Get(resGroup, name)
if resp.StatusCode == http.StatusNotFound {
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("Error making Read request on Azure RM Template Deployment %s: %s", name, err)
}
var outputs map[string]string
if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 {
for key, output := range *resp.Properties.Outputs {
log.Printf("[INFO] Found Key %s", key)

outputMap := output.(map[string]interface{})
outputValue, ok := outputMap["value"]
if !ok {
// No value
continue
}

outputs[key] = outputValue.(string)
}
}
d.Set("outputs", outputs)

return nil
}

func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient)
deployClient := client.deploymentsClient

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

_, err = deployClient.Delete(resGroup, name)
return nil
}

func expandTemplateBody(template string) (map[string]interface{}, error) {
var templateBody map[string]interface{}
err := json.Unmarshal([]byte(template), &templateBody)
if err != nil {
return nil, fmt.Errorf("Error Expanding the template_body for Azure RM Template Deployment")
}
return templateBody, nil
}

func normalizeJson(jsonString interface{}) string {
if jsonString == nil || jsonString == "" {
return ""
}
var j interface{}
err := json.Unmarshal([]byte(jsonString.(string)), &j)
if err != nil {
return fmt.Sprintf("Error parsing JSON: %s", err)
}
b, _ := json.Marshal(j)
return string(b[:])
}

func templateDeploymentStateRefreshFunc(client *ArmClient, resourceGroupName string, name string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
res, err := client.deploymentsClient.Get(resourceGroupName, name)
if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in templateDeploymentStateRefreshFunc to Azure ARM for Template Deployment '%s' (RG: '%s'): %s", name, resourceGroupName, err)
}

return res, strings.ToLower(*res.Properties.ProvisioningState), nil
}
}
Loading