Search code examples
azure-pipelinesazure-devops-rest-api

Referencing variables in yaml that are passed from ADO REST Api


I want to run a pipeline i have with variables which are being sent from an application in a POST request to ADO pipeline. Trying to do something similar to this post with runs api: However I'm not sure how to reference these variables in my pipeline. I want to use terraform in my pipeline with some of these variables. This may be something simple I just have not found yet but any help is appreciated

I have searched online and some places say environment variables? Would appreciate help in how to reference these if thats the case.


Solution

  • To reference a pipeline variable assigned via the REST API Runs - Run Pipeline in terraform, you can refer to the following example. In this example, I create a new project and define the name of the project using the variable "projname".

    1. Declare the variable projname and refer to it using var.projname in main.tf.
    variable "projname" {
      type = string
    }
    
    terraform {
      required_providers {
        azuredevops = {
          source = "microsoft/azuredevops"
          version = ">= 0.1.0"
        }
      }
    }
    
    resource "azuredevops_project" "project" {
      name               = var.projname
      visibility         = "private"
      version_control    = "Git"
      work_item_template = "Agile"
      description        = "Created by Terraform"
    }
    
    1. Add a variable named "projname" in the UI and leave its value empty. enter image description here

    2. Passs the value of projname to the terraform scripts using -var "projname=$(projname)" in your plan and apply command.

    - task: CmdLine@2
      displayName: Terraform Plan and Apply
      env: 
        AZDO_PERSONAL_ACCESS_TOKEN: $(System.AccessToken)
        AZDO_ORG_SERVICE_URL: $(System.CollectionUri)
      inputs:
        script: |
          terraform plan -input=false -var "projname=$(projname)"
          terraform apply -input=false -var "projname=$(projname)" -auto-approve
    
    

    If you are not making changes to DevOps org, there is no need to define env variables shown above.

    If you are using Terraform task, you can add -var "projname=$(projname)" in commandOptions.

    - task:TerraformTaskV3@3
      displayName: 'Terraform Plan'
      inputs:
        command: 'plan'
        workingDirectory: '$(Build.SourcesDirectory)'
        environmentServiceName: '<service_connection_name>'
        commandOptions: '-var "projname=$(projname)"'
    
    1. Run REST API Runs - Run Pipeline to trigger the pipeline.

    Request body:

    {
        "resources": {
            "repositories": {
                "self": {
                    "refName": "refs/heads/main"
                }
            }
        },
        "variables": {
            "projname": {
                "isSecret": false,
                "value": "TerraformPro"
            }
        }
    }