2
votes

I am trying to create an Azure DevOps pipeline to build out a terraform environment in Azure. I wish the tfstate file to be remote in an Azure Storage account. There are lots of simple examples to do this if you wish the storage account to remain publicly accessible.

However I do not. I would like to restrict access to the storage account using a SAS Token.

However I am having a hard time:

  1. Finding reasonable references on this subject.
  2. Finding anything that helps me define the sas token in the pipeline yaml.

My idea was that the SAS Token would be a security pipeline variable or part of a variable group which would then be inserted into the pipeline yaml, and then passed to the underlying terraform.

Attempts at trying script and TerraformTaskV1 contructs have failed. The latest error I received during the pipeline build for the init command is:

Error: Failed to get existing workspaces: storage: service returned error: StatusCode=403, ErrorCode=AuthorizationFailure, ErrorMessage=This request is not authorized to perform this operation.

I believe this is telling me that the sas token definition is failing because its not being applied. I have tested the token manually in a VM in our subscription.

Here is the current attempt:

- task: ms-devlabs.custom-terraform-tasks.custom-terraform-release-task.TerraformTaskV1@0
    displayName: 'Terraform init'
    inputs:
      provider: 'azurerm'
      command: 'init'
      workingDirectory: '$(System.DefaultWorkingDirectory)/modules/terraform/basic-sastoken'
      backendServiceArm: $(service_connection)
      backendAzureRmResourceGroupName: $(resource_group_name)
      backendAzureRmStorageAccountName: $(storage_account_name)
      backendAzureRmContainerName: $(container_name)
      backendAzureRmKey: $(key)
      commandOptions: -input=false -var "sastoken=$(sas_token)"

Ok, so what are my options?

Is this an impossible task? Is this not supported outside a narrow Microsoft Happy Path? Do I need to build my own agent and scale set? Would that even help. Are there any decent references?

1

1 Answers

1
votes

Please do not use a SAS token but a service principal to access the storage account. Give the SP contributer rights on the storage account and you should be good to go!

steps:
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-release-task.TerraformTaskV1@0
  displayName: 'Terraform : init'
  inputs:
    workingDirectory: '$(System.DefaultWorkingDirectory)/<YOUR TERRAFORM FILES>'
    backendServiceArm: '<SERVICE CONNECTION YOU CREATED>'
    backendAzureRmResourceGroupName: '<RESOURCE GROUP YOUR STATE STORAGE ACCOUNT IS LOCATED'
    backendAzureRmStorageAccountName: <NAME OF STORAGE ACCOUNT WITH STATE>
    backendAzureRmContainerName: <CONTAINER NAME>
    backendAzureRmKey: '<TERRAFORM STATE KEY>'

Remove the <> with your value. Regarding the service connection, you can create it in DevOps :).