Skip to content

Commit

Permalink
Merge pull request #404 from civascu/enhancement_arm_template_params
Browse files Browse the repository at this point in the history
`azurerm_template_deployment` - support for specifying parameters via `parameters_body`
  • Loading branch information
tombuildsstuff authored Mar 14, 2018
2 parents 3378abf + 35b7e68 commit 93fad3a
Show file tree
Hide file tree
Showing 3 changed files with 209 additions and 6 deletions.
44 changes: 38 additions & 6 deletions azurerm/resource_arm_template_deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

Expand Down Expand Up @@ -39,18 +40,31 @@ func resourceArmTemplateDeployment() *schema.Resource {
},

"parameters": {
Type: schema.TypeMap,
Optional: true,
Type: schema.TypeMap,
Optional: true,
ConflictsWith: []string{"parameters_body"},
},

"outputs": {
Type: schema.TypeMap,
Computed: true,
"parameters_body": {
Type: schema.TypeString,
Optional: true,
StateFunc: normalizeJson,
ConflictsWith: []string{"parameters"},
},

"deployment_mode": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(resources.Complete),
string(resources.Incremental),
}, true),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},

"outputs": {
Type: schema.TypeMap,
Computed: true,
},
},
}
Expand All @@ -65,7 +79,7 @@ func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{
resourceGroup := d.Get("resource_group_name").(string)
deploymentMode := d.Get("deployment_mode").(string)

log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.")
log.Printf("[INFO] preparing arguments for AzureRM Template Deployment creation.")
properties := resources.DeploymentProperties{
Mode: resources.DeploymentMode(deploymentMode),
}
Expand All @@ -85,6 +99,15 @@ func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{
properties.Parameters = &newParams
}

if v, ok := d.GetOk("parameters_body"); ok {
params, err := expandParametersBody(v.(string))
if err != nil {
return err
}

properties.Parameters = &params
}

if v, ok := d.GetOk("template_body"); ok {
template, err := expandTemplateBody(v.(string))
if err != nil {
Expand Down Expand Up @@ -209,6 +232,15 @@ func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{
}

// TODO: move this out into the new `helpers` structure
func expandParametersBody(body string) (map[string]interface{}, error) {
var parametersBody map[string]interface{}
err := json.Unmarshal([]byte(body), &parametersBody)
if err != nil {
return nil, fmt.Errorf("Error Expanding the parameters_body for Azure RM Template Deployment")
}
return parametersBody, nil
}

func expandTemplateBody(template string) (map[string]interface{}, error) {
var templateBody map[string]interface{}
err := json.Unmarshal([]byte(template), &templateBody)
Expand Down
167 changes: 167 additions & 0 deletions azurerm/resource_arm_template_deployment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,26 @@ func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) {
})
}

func TestAccAzureRMTemplateDeployment_withParamsBody(t *testing.T) {
ri := acctest.RandInt()
config := testaccAzureRMTemplateDeployment_withParamsBody(ri, testLocation())
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"),
resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.testOutput", "Output Value"),
),
},
},
})

}

func TestAccAzureRMTemplateDeployment_withOutputs(t *testing.T) {
ri := acctest.RandInt()
config := testAccAzureRMTemplateDeployment_withOutputs(ri, testLocation())
Expand Down Expand Up @@ -301,6 +321,153 @@ DEPLOY
`, rInt, location, rInt)
}

func testaccAzureRMTemplateDeployment_withParamsBody(rInt int, location string) string {
return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
name = "acctestRG-%d"
location = "%s"
}
output "test" {
value = "${azurerm_template_deployment.test.outputs["testOutput"]}"
}
resource "azurerm_storage_container" "using-outputs" {
name = "vhds"
resource_group_name = "${azurerm_resource_group.test.name}"
storage_account_name = "${azurerm_template_deployment.test.outputs["accountName"]}"
container_access_type = "private"
}
data "azurerm_client_config" "current" {}
resource "azurerm_key_vault" "test-kv" {
location = "%s"
name = "acctestKv-%d"
resource_group_name = "${azurerm_resource_group.test.name}"
"sku" {
name = "standard"
}
tenant_id = "${data.azurerm_client_config.current.tenant_id}"
enabled_for_template_deployment = true
access_policy {
key_permissions = []
object_id = "${data.azurerm_client_config.current.service_principal_object_id}"
secret_permissions = [
"all"]
tenant_id = "${data.azurerm_client_config.current.tenant_id}"
}
}
resource "azurerm_key_vault_secret" "test-secret" {
name = "acctestsecret-%d"
value = "terraform-test-%d"
vault_uri = "${azurerm_key_vault.test-kv.vault_uri}"
}
data "template_file" "test-template" {
template = <<TPL
{
"dnsLabelPrefix": {
"reference": {
"keyvault": {
"id": "/subscriptions/$${subscription_id}/resourceGroups/$${vault_resource_group_name}/providers/Microsoft.KeyVault/vaults/$${vault_name}"
},
"secretName": "$${secret_name}"
}
},
"storageAccountType": {
"value": "Standard_GRS"
}
}
TPL
vars {
"subscription_id" = "${data.azurerm_client_config.current.subscription_id}"
"vault_resource_group_name" = "${azurerm_resource_group.test.name}"
"vault_name" = "${azurerm_key_vault.test-kv.name}"
"secret_name" = "${azurerm_key_vault_secret.test-secret.name}"
}
}
resource "azurerm_template_deployment" "test" {
name = "acctesttemplate-%d"
resource_group_name = "${azurerm_resource_group.test.name}"
template_body = <<DEPLOY
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"storageAccountType": {
"type": "string",
"defaultValue": "Standard_LRS",
"allowedValues": [
"Standard_LRS",
"Standard_GRS",
"Standard_ZRS"
],
"metadata": {
"description": "Storage Account type"
}
},
"dnsLabelPrefix": {
"type": "string",
"metadata": {
"description": "DNS Label for the Public IP. Must be lowercase. It should match with the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$ or it will raise an error."
}
}
},
"variables": {
"location": "[resourceGroup().location]",
"storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]",
"publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]",
"publicIPAddressType": "Dynamic",
"apiVersion": "2015-06-15"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"apiVersion": "[variables('apiVersion')]",
"location": "[variables('location')]",
"properties": {
"accountType": "[parameters('storageAccountType')]"
}
},
{
"type": "Microsoft.Network/publicIPAddresses",
"apiVersion": "[variables('apiVersion')]",
"name": "[variables('publicIPAddressName')]",
"location": "[variables('location')]",
"properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]",
"dnsSettings": {
"domainNameLabel": "[parameters('dnsLabelPrefix')]"
}
}
}
],
"outputs": {
"testOutput": {
"type": "string",
"value": "Output Value"
},
"accountName": {
"type": "string",
"value": "[variables('storageAccountName')]"
}
}
}
DEPLOY
parameters_body = "${data.template_file.test-template.rendered}"
deployment_mode = "Complete"
depends_on = ["azurerm_key_vault_secret.test-secret"]
}
`, rInt, location, location, rInt, rInt, rInt, rInt)

}

func testAccAzureRMTemplateDeployment_withParams(rInt int, location string) string {
return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
Expand Down
4 changes: 4 additions & 0 deletions website/docs/r/template_deployment.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ The following arguments are supported:

* `parameters` - (Optional) Specifies the name and value pairs that define the deployment parameters for the template.

* `parameters_body` - (Optional) Specifies a valid Azure JSON parameters file that define the deployment parameters. It can contain KeyVault references

~> **Note:** There's an [`file` interpolation function available](https://www.terraform.io/docs/configuration/interpolation.html#file-path-) which allows you to read this from an external file, which helps makes this more resource more readable.

## Attributes Reference

The following attributes are exported:
Expand Down

0 comments on commit 93fad3a

Please sign in to comment.