
For infrastructure as code I am using packer (Build Immutable image) task to create a gold image. I then want to pass the image URI to Terraform so it can spin up servers or scale sets. Since I like to add date/time in our packer image name then the name is not static so we have to save the resource ID somewhere after a successful packer build so that Terraform is aware of which image to use.
We can accomplish this with a 3 task pipeline that uses packer and the Azure DevOps CLI to manage the variable group’s variables so that we can store the image resource ID and use it in other places like our release pipeline.
Pipeline Overview.

Let’s break it down:
I. Build machine image: Packer
The key here is to configure your outputs correctly. Once you capture the Azure Resource ID in your variable you then reference it in the output variables so that other tasks can use it.

II. (Optional) Display the Resource ID
For testing you can add a step to make sure you are getting the correct value

III. Azure DevOps CLI
Make sure your agent has the azure-cli installed. I am using on prem ubuntu agents so I installed it and configured the organization as a default value:
sudo apt install azure-cli
azdorg=https://dev.azure.com/companyname
az devops configure --defaults organization=$azdorg
az devops configure --defaults project=projectname
Once the defaults are set you can configure the next step which is to login to the azure devops CLI using the personal access token.

You must use az devops login when using a personal access token and we set the environment variable to use the $(System.AccessToken) but in order for this to work you have to let the scripts in tasks access the OAuth token with the following checkbox.

IV. Set the variable in the variable group.
First create the variable group that will store the Image Resource ID

Add permissions so that the build service can not only read but also update the variables.

Now that the variable group is created and permissions are set you can create the task to run the azure devops cli command to update a variable in a variable group.
az pipelines variable-group variable update --group-id # --name imageuri --value $(bakedimgazid)

V. Result
When you run your pipeline packer will create the image, output the Image Resource ID and the bash one liners will update the variable group with the new IDs so you can then use this in release pipelines and build VMs, scale sets, etc.
