Social

onsdag den 19. oktober 2016

CustomScriptExtension in ARM Templates and Shared Access Signature (SAS) Tokens

I had some trouble with a custom script extension where the script required a SAS token to download some software. The token was simply truncated after the first '&'.

After some digging I thought I had to put the SAS token into quotes, and when looking into C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.8\RuntimeSettings\0.settings I found that it was a sensible solution. I could also copy the "commandToExecute" and run it and get the expected result. In the variables section I added a:


  "variables": {
    "singlequote": "'",

And then put single quotes around the parameters('SASToken'). But no dice. The token was still getting truncated, this time with a 'in front...

So I decided to get rid of the '&', at least temporarily. base64 encoding to the rescue. And Luckily there is an ARM template function for just that. In the script I then added:

$SASToken = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($SASToken))

Problem solved!

Seems to me that there is something odd in how the custom script extension calls PowerShell in this particular instance.

onsdag den 5. oktober 2016

Begin..Process..End and Error Handling

I had to wrap my mind around error handling and the begin..process..end function in PowerShell. It becomes really fun when I start throwing different ErrorActions after it!

This will be mostly some PowerShell snippets and their result. So without further ado, lets dive into some code!

This is a really simple function:

function myfunc
{
    [cmdletbinding()]
    param()

    begin
    {
        # some init code that throws an error
        try
        {
            throw 'some error'
            # code never reaches here
            Write-Output 'begin block'
        }
        catch [System.Exception]
        {
            Write-Error 'begin block'
        }
    }
    process
    {
        Write-Output 'process block'
    }
    end
    {
        Write-Output 'end block'
    }
}
Clear-Host
$VerbosePreference = "Continue"

Write-Host "-ErrorAction SilentlyContinue: the Write-Error in the begin block is suppressed" `
    -ForegroundColor Cyan
myfunc -ErrorAction SilentlyContinue
Write-Host "-ErrorAction Continue: displays the Write-Error in the begin block,
but the process and end block is executed" `
    -ForegroundColor Cyan
myfunc -ErrorAction Continue
Write-Host "-ErrorAction Stop: displays the Write-Error in the begin block. 
The Write-Error in the begin block becomes a terminating error. 
The process and end block is not executed" `
    -ForegroundColor Cyan
myfunc -ErrorAction Stop

The output is:




We see that for both ErrorActions Continue/SilentlyContinue that the process block is executed. When we use Stop then Write-Error becomes a terminating error and the pipeline is stopped.

Let us not dwell on that and move onto a function with some actual input:

# with input
function myfunc
{
    [cmdletbinding()]
    param(
        [Parameter(
            Position=0, 
            Mandatory=$true, 
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)
        ]
        $x
    )

    begin
    {
        # No errors in the begin block this time
        Write-Output 'begin block'
    }
    process
    {
        if($x -gt 2)
        {
            Write-Error "$x is too big to handle!"
        }
        # echo input
        Write-Output $x
    }
    end
    {
        Write-Output 'end block'
    }
}
Clear-Host
$VerbosePreference = "Continue"

Write-Host "-ErrorAction SilentlyContinue: the Write-Error in the process block is suppressed" `
    -ForegroundColor Cyan
@(1,2,3) | myfunc -ErrorAction SilentlyContinue

Write-Host "-ErrorAction Continue: The Write-Error in the process block is displayed,
but `$x is still echoed" `
    -ForegroundColor Cyan
@(1,2,3) | myfunc -ErrorAction Continue

Write-Host "-ErrorAction Stop: The Write-Error in the process block becomes a terminating error, 
`$x > 2 is NOT echoed" `
    -ForegroundColor Cyan
@(1,2,3) | myfunc -ErrorAction Stop

The output is:



Now we see that something uninteded is happening for both ErrorActions Continue/SilentlyContinue. 3 is echoed still. With Stop the story is as before, Write-Error becomes a terminating error and 3 is not echoed.

Now we basically just add a return statement:

# with input
function myfunc
{
    [cmdletbinding()]
    param(
        [Parameter(
            Position=0, 
            Mandatory=$true, 
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)
        ]
        $x
    )

    begin
    {
        # No errors in the begin block this time
        Write-Output 'begin block'
    }
    process
    {
        if($x -gt 2)
        {
            Write-Error "$x is too big to handle!"
            # continue on the pipeline. NOTE: continue does NOT continue but rather shuts down the pipeline completely
            return
        }
        # echo input
        Write-Output $x
    }
    end
    {
        Write-Output 'end block'
    }
}
Clear-Host
$VerbosePreference = "Continue"

Write-Host "-ErrorAction SilentlyContinue: the Write-Error in the process block is suppressed
(for both 3 and 4), and `$x > 2 is not echoed" `
    -ForegroundColor Cyan
@(1,2,3,4) | myfunc -ErrorAction SilentlyContinue

Write-Host "-ErrorAction Continue: The Write-Error in the process block is displayed
(twice, for both 3 and 4). `$x > 2 is not echoed" `
    -ForegroundColor Cyan
@(1,2,3,4) | myfunc -ErrorAction Continue
Write-Host 'The script keeps running' `
    -ForegroundColor Cyan

Write-Host "-ErrorAction Stop: The Write-Error in the process block becomes a terminating error,
'3' is NOT echoed. return is not exectuted hence the pipeline stops" `
    -ForegroundColor Cyan
@(1,2,3,4) | myfunc -ErrorAction Stop
Write-Host 'this is not reached' `
    -ForegroundColor Cyan

The output is:



We see that in all 3 cases that x greater than 2 is not echoed. Now ErrorAction Stop makes sense. We indicate that if the function fails for any input we do not wish to continue the script.

And we can add some error handling:

# with input
function myfunc
{
    [cmdletbinding()]
    param(
        [Parameter(
            Position=0, 
            Mandatory=$true, 
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)
        ]
        $x
    )

    begin
    {
        # No errors in the begin block this time
        Write-Output 'begin block'
    }
    process
    {
        try
        {
            if($x -gt 2)
            {
                # this puts the error into the $Error variable
                throw "$x is too big to handle!"

            }
            # echo input
            Write-Output $x
            }
        catch [System.Exception]
        {
            Write-Error $Error[0].Exception
            Write-Verbose "continue on the pipeline '$x'"
            return
        }
        Write-Verbose "continue on the pipeline '$x'"
    }
    end
    {
        Write-Output 'end block'
    }
}
Clear-Host
$VerbosePreference = "Continue"

Write-Host "-ErrorAction SilentlyContinue: the Write-Error in the process block is suppressed 
(for both 3 and 4), and `$x is not echoed" `
    -ForegroundColor Cyan
@(1,2,3,4) | myfunc -ErrorAction SilentlyContinue

Write-Host "-ErrorAction Continue: The Write-Error in the process block is displayed 
(twice, for both 3 and 4).`$x is not echoed" `
    -ForegroundColor Cyan
@(1,2,3,4) | myfunc -ErrorAction Continue
Write-Host 'The script keeps running' `
    -ForegroundColor Cyan

Write-Host "-ErrorAction Stop: The Write-Error in the process block becomes a terminating error, 
'3' is NOT echoed. return is not exectuted and the pipeline stops" `
    -ForegroundColor Cyan
@(1,2,3,4) | myfunc -ErrorAction Stop
Write-Host 'this is not reached' `
    -ForegroundColor Cyan

The output is:


I hope this helps understanding how some of the begin..process..end function works with regards to errors and error handling. I know I will be returning to this from time and again :D


tirsdag den 4. oktober 2016

ARM Template Tip: Names

Naming resources in ARM templates can be quite lengthy. This is an example of naming a network interface:

"name": "[concat(parameters('vmNamePrefix'), '-', padLeft(copyIndex(1), 2, '0'), variables('nicPostfix'), '-', padLeft(copyIndex(1), 2, '0'))]",

And we have to reference this at a later point for the virtual machine resource. If we then change the name, we will have to remember to change this reference also.

What we can do is to define the name in the variables section like this:

    "nic": {
      "name": "[concat(parameters('vmNamePrefix'), '-', padLeft('{0}', 4, '0'), variables('nicPostfix'), '-', padLeft('{0}', 4, '0'))]"
    }

(I like to group variables). And then reference this variable in the resource like:

"name": "[replace(variables('nic').name, '{0}', string(copyIndex(1)))]",

What I have done is to make {0} a placeholder and then replace it with the result from copyIndex(). We now have a central location to change the name if needed with no need to update any resources.

Would be cool if we had a template function for formatting:

"name": "[format(variables('nic').name, copyIndex(1), '-nic')]"

It would take the string as input and then a variable number of additional arguments. Ex.


"nic": {
   "name": "concat(parameters('vmNamePrefix'), '0{0}', '{1}')]"
}

would become({0} is replaced with the result from copyIndex(1) and {1} replaced with -nic):

"VM01-nic"

And it could be made more advanced, perhaps leaning on the good ol' sprintf.

Søg i denne blog