Provision and storing Terraform backend state remotely to use with TerraformTaskV1@0

Terraform must store state about your Azure Infrastructure and additional configurations. This “state” is used by Terraform to plan against any related real world resources. It uses the state to create the plan when you run “terraform plan” and also used to make any changes to your infrastructure; including any additions and removals.

The state itself is stored by default in a local file called “terraform.state”; this file can be stored remotely.

Lets have a look at the TerraformTaskV1@0 task and inputs required:-

              - task: TerraformTaskV1@0
                displayName: 'init'
                inputs:
                  provider: 'azurerm'
                  command: 'init'
                  backendServiceArm: 'tamopstf'
                  backendAzureRmResourceGroupName: ''
                  backendAzureRmStorageAccountName: ''
                  backendAzureRmContainerName: ''
                  backendAzureRmKey: ''
                  workingDirectory: '$(System.DefaultWorkingDirectory)/terraform/'

The terraform state file is required to be stored inside an Azure Storage Blob Container.

I will be storing my state file in a Storage Account container called:- tfstatedevops

Lets deploy the required storage container called tfstatedevops in Storage Account tamopstf inside Resource Group tamopstf

Terraform must store state about your managed infrastructure and configuration. This state is used by Terraform to map real world resources to your configuration, keep track of metadata, and to improve performance for large infrastructures.

#Create Resource Group
New-AzureRmResourceGroup -Name "tamopstf" -Location "eastus2"
 
#Create Storage Account
New-AzureRmStorageAccount -ResourceGroupName "tamopstf" -AccountName "tamopstf" -Location eastus2 -SkuName Standard_LRS
 
#Create Storage Container
New-AzureRmStorageContainer -ResourceGroupName "tamopstf" -AccountName "tamopstf" -ContainerName "tfstatedevops"


Once this container is created, we can now enter the required inputs for the TerraformTaskV1@0 task

backendAzureRmKey has not yet been created as the Pipeline has not been ran, I have entered terraform.tfstate below; this file will be appended to once a pipeline has been ran.

              - task: TerraformTaskV1@0
                displayName: 'init'
                inputs:
                  provider: 'azurerm'
                  command: 'init'
                  backendServiceArm: 'tamopstf'
                  backendAzureRmResourceGroupName: 'tamopstf'
                  backendAzureRmStorageAccountName: 'tamopstf'
                  backendAzureRmContainerName: 'tfstatedevops'
                  backendAzureRmKey: 'terraform.tfstate'
                  workingDirectory: '$(System.DefaultWorkingDirectory)/terraform/'

Now ready to run the pipeline as the backend state has been provisioned and ready to go!

Leave a Reply