Home > Blockchain >  Split azure metadata tags with semicolon in value
Split azure metadata tags with semicolon in value

Time:09-09

The azure metadata api returns tags in the format key:value joined by a semicolon.

How do I split the following set of tags, without splitting on the values that are also separated by a semicolon.

The tags are any key:value pair the user would like to attach to the VM.

Examples:

tag1:value1;tag2:valueA;valueB;valueC;tag3:value3
joe:bloggs;jane:doe;female;foo:bar
'tag1:value1;tag2:valueA;valueB;valueC;tag3:value3'.split(';')
tag1:value1
tag2:valueA
valueB
valueC
tag3:value3

What I need is

tag1:value1
tag2:valueA;valueB;valueC
tag3:value3

You can query the azure metadata api using the following:

$meta = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
$meta.compute.tags

Azure Instance Metadata Service

CodePudding user response:

probably there are more elegant regex solutions. but at least it works, as long as there is no : within a value:

$arrayList = new-object collections.generic.list[string]
'tag1:value1;tag2:valueA;valueB;valueC;tag3:value3' -split ";" | %{
    If ($_ -match ":"){
        $arrayList.add($_)
    }
    Else{
        $arrayList[-1] = $arrayList[-1]   ';'   $_
    }
}

tag1:value1
tag2:valueA;valueB;valueC
tag3:value3
  • Related