Data Dealings

July 27, 2016

Azure Template Extraction

Packer prints out some details at the completion of each packer build run for Azure systems. That detail includes a Shared Access Signature URL for the image template required to execute an azure group deployment create command to get a virtual machine up and running.

There are a couple of packer command-line switches to accommodate the extraction of that information so that it can be fed programmatically in to a deployment pipeline:


You can use those switches and redirect the output of the packer command to a file. With that file available, you can then parse it to extract the template URI. I wrote a quick Python script to do just that:

#!/usr/bin/env python

import fileinput

print [c for x in fileinput.input() \
       for a in x.split(',') \
       for c in a.split("\\n") \
       if "TemplateUriReadOnlySas: " in c][0].split(' ')[1]

The comprehension does the following:

  1. Loop through a file piped in via STDIN.
  2. Split each comma-delimited (that's the effect of -machine-readable) line into a list.
  3. Split each item in the lists from step 2 at the newline character.
  4. Only capture the list item from 3 that contains "TemplateUriReadOnlySas: ". This will always be at the beginning, but I just look for it anywhere in the string.
  5. Grab the first element in the composed list (it will only be one item) and split that at the white space.
  6. Return the second element in the list from 5.

I don't have the opportunity to write list comprehensions often, so I might go a little overboard when I do. But I prefer that to a bunch of nested for loops.

This is pretty brittle. If the build failed for some reason, that print command is likely to throw a tantrum because the list comprehension won't produce a list (and hence there will be no item [0]). But it gets the basic job done.