Search code examples
azurepowershellazure-devopsazure-cli

How to import json file saved in local directory (desktop) to Azure DevOps Library Variable Group using az cli?


This is contents for the json file

{
  "authorized": false,
  "description": "Holds general variables",
  "name": "Var",
  "providerData": null,
  "type": "Vsts",
  "variables": {
    "Var1": {
      "isSecret": false,
      "value": "TestVar1"
        },
    "Var2": {
      "isSecret": false,
      "value": "TestVar2"
        }
    }
}

This is what I was trying to run.

$json = Get-Content -Path C:\variables\var.json out-string | out-string 

$name = $json | ConvertFrom-Json
$varname = $name.variables

az pipelines variable-group create --name 'Var' --variables $varname --description 'This is a test variable' --detect false --org 'https://dev.azure.com/{organization}' --project '{project name or id}' 

Any help would be appreciated as I have multiple variables to import to Azure DevOps.


Solution

  • How to import json file saved in local directory (desktop) to Azure DevOps Library Variable Group using az cli?

    Here is the updated script for creating a variable group with multiple variables inside the group, collected from the 'var.json' file using Azure CLI

        $json = Get-Content -Path "C:\Venkat\Venkat\var.json" | Out-String
        $variableGroup = $json | ConvertFrom-Json
    
        $groupName = $variableGroup.name
        $description = $variableGroup.description
        $variablesObject = $variableGroup.variables
        
        $variablesHashtable = @{}
        foreach ($property in $variablesObject.PSObject.Properties) {
            $variableName = $property.Name
            $variableValue = $property.Value.value
            $variablesHashtable[$variableName] = $variableValue
        }
        $variablesString = $variablesHashtable.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }
        
        # Create variable group using Azure CLI
        az pipelines variable-group create --name $groupName --variables $variablesString --description $description --detect false --org 'https://dev.azure.com/<org-Name>' --project '<Project-name>'
    

    Output:

    enter image description here

    Once the script is run, the variable group and variables are created in my project.

    enter image description here