Monday 26 April 2021

Pass Map Type Parameters to Terraform via Azure Pipelines

Terraform based resource deployment to Azure is a great way to implement infrastructure as code. The map type in variables support implementing loop-based resource deployment specifications in terraform. It is important to understand passing such variable as parameter in command line to implement pipelines.

For example, below variable can be used to create multiple subnets in a given vnet. It specifies the IP addresses as well for each subnet.


The resource block such as below can handle the deployment of subnets in a loop.


Now about passing the parameter via command line requires the variable to be something like below. Note the triple usage of double quotes. It is mandatary to have it like that to get the parameter passed correctly to terraform commands.

-var='subnets={snet-qqweb-prod={snetAdressPrefix=["""2.2.2.0/28"""]}}'

If two subnets like below

-var='subnets={snet-qqweb-prod={snetAdressPrefix=["""2.2.2.0/28"""]},snet-qqapp-prod={snetAdressPrefix=["""2.2.2.16/28"""]}}'

A plan command would similar to below

terraform plan -out='prod.tfplan' -state='prod-rg-qqvnet-prod.tfstate' -var='AzureSubscriptionId=xxxxxxxxxxxx' -var='AzureSPNAppId=xxxxxx' -var='AzureSPNPwd=xxxxxx' -var='AzureTenantId=xxxxxxxx' -var='resourceGroupNamevNet=rg-qqvnet-prod' -var='location=eastus' -var='vNetName=vnet-qp-prod' -var='subnets={snet-qqweb-prod={snetAdressPrefix=["""2.2.2.0/28"""]},snet-qqapp-prod={snetAdressPrefix=["""2.2.2.16/28"""]}}'

You can define variable in Azure DevOps library or in release to hold subnets similar to below string.

'subnets={snet-qqweb-prod={snetAdressPrefix=["""2.2.2.0/28"""]},snet-qqapp-prod={snetAdressPrefix=["""2.2.2.16/28"""]}}

Then use a command line task in the pipeline to execute the plan command similar to below.

terraform plan -out='prod.tfplan' -state='prod-rg-qqvnet-prod.tfstate' -var='AzureSubscriptionId=xxxxxxxxxxxx' -var='AzureSPNAppId=xxxxxx' -var='AzureSPNPwd=xxxxxx' -var='AzureTenantId=xxxxxxxx' -var='resourceGroupNamevNet=$('resourceGroupNamevNet)' -var='location=$(location)' -var='vNetName=$(vNetName)' -var='subnets=$(subnets)'

No comments:

Popular Posts