PowerShell based Validations
  • 19 Jan 2025
  • 13 Minutes to read
  • Contributors
  • Dark
    Light

PowerShell based Validations

  • Dark
    Light

Article summary

Overview

Validations are used by CloudLabs to enable Instructors to verify whether the students/attendees have done their labs in the way they are expected to.CloudLabs currently enables Admins to author custom PowerShell validations based on Azure and AWS. In addition to Cloud specific PowerShell commands, we can utilize the capabilities of PowerShell to call APIs to author even more specific validation commands. The below sections will guide you on how to make the most of PowerShell while authoring Validations for your labs.

How to configure Validations

  1. Navigate to CloudLabs Template(1) that you have created then click on edit button under Actions pane(2)


  2. Once you are inside the Template Navigate to the Course Details section of the Template and then click on the Manage Button as shown below.

  3. On the 'Manage Page,' you will find the option to add Validation Steps. Please click on the Add button, which is depicted below.


  4. An Add Module Tab will open in the right side. Modules can be equivalent to the exercises in the lab, which are nothing but a collection of tasks. Tasks are comprised of a series of steps. Enter your preferred Name and Description for the module and click on the Submit button.

  5. Once the Module is added, you’ll have the provision to add steps for validation of Labs/Lectures/Quizzes. This can be treated as equivalent to the tasks within the Exercises. Click on the + button corresponding to Labs/Lectures/Quizzes.


  6. In the Add Lecture/Lab/Quiz section, Select the Type as Lab and give a preferred name for identification of the step and then click on Submit. Rest of the fields are not mandatory.

  7. Now that the step has been defined in the previous step, it's time to add the Validation script. After clicking 'Submit' in the previous step, the Step will appear under the Validation Module section. Click on the black tab labeled with the Validation Step name, then click the + button.

  1. In the Add Step section details can be entered and configured. This is equivalent to the steps inside the tasks. The supported Validation Types will be discussed in the upcoming sections and how to configure each will be described in detail.


PowerShell based Validations for Azure

CloudLabs supports PowerShell-based validations for Azure. To enable the execution of PowerShell scripts in Azure, CloudLabs has integrated the Az Module. Below are the instructions on how to create a PowerShell-based validation for your Azure lab

  1. Follow Steps 1 to 8 of the above section, How to Configure Validations to create a Validation Step. Once you are in the Add Step window, follow the next steps to configure a PowerShell based Azure Validation Step.

  2. A script can be configured as follows:

    • Name: Validate Virtual Network (Enter a name of your preference. This will appear in the lab details page of the user)

    • Validation Type: Custom

    • Score: 0 (Enter a value of your preference)

    • Script Type: PowerShellV2

    • Script: Sample script will be provided below

    • Parameters: List of Supported Parameters will be given below

    • Run As: System
      NOTE: When you choose Run as SYSTEM, the execution will happen from the CloudLabs context from the Service Principal used for CloudLabs. If you choose Run as AAD Principal, you will have to ensure that the Create Service Principal flag is enabled at the Template level.

  1. After entering the required details, click on Submit

  2. Below Provided is the sample Az PowerShell script used in the above scenario which detects whether a Virtual Network is created in the user environment.


$stopRetry = $false

[int]$retryCount = "3"

do{

    try{

        Set-AzContext -Subscription $SubscriptionId

        $vnet = Get-AzVirtualNetwork -ResourceGroupName $rg

        if ($vnet.Count -gt 0)  

        {   

        $vnetCount = $vnet.Count   

         $message = @{Status ="Succeeded"; Message = "virtual network was found"}| ConvertTo-Json

                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{

                                StatusCode = [System.Net.HttpStatusCode]::OK

                                Body = $message})

        $stopRetry = $true

        }

        else {

            $message = @{Status ="Failed"; Message ="virtual network was not found."}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message})

        $stopRetry = $true
 
        }

    }

    catch {

        if ($retryCount -gt 3){

                $message = @{Status ="Failed"; Message ="Retry for validation process has been exhausted. Please try after sometime."}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message})

                $stopRetry = $true

            }

        else {

                Write-Host "Tried validating three times and the VNet does not exist."

                Start-Sleep -Seconds 60
 
                $Retrycount = $Retrycount + 1

            }

    }

}while ($stopRetry -eq $false) {

}

PowerShell based Validations for AWS

CloudLabs supports PowerShell-based validations for AWS. To enable the execution of PowerShell scripts in AWS, CloudLabs has integrated the AWSPowerShell. Below are the instructions on how to create a PowerShell-based validation for your AWS lab

  1. Follow Steps 1 to 8 of the above section, How to Configure Validations to create a Validation Step. Once you are in the Add Step window, follow the next steps to configure a PowerShell based AWS Validation Step.

  2. A script can be configured as follows:

    • Name: Creation of EC2 instance (Enter a name of your preference. This is will appear in the lab details page of the user)

    • Validation Type: Custom

    • Score: 0 (Enter a value of your preference)

    • Script Type: PowerShellV2

    • Script: Sample script will be provided below

    • Parameters: List of Supported Parameters will be given below

    • Run As: System

  1. After entering the required details, click on Submit

  1. Below provided is a sample PowerShell script which can be added to validate whether EC2 instances are created in the AWS account.

# Get EC2 instances with the specified name
do{
try {
$instances = Get-EC2Instance -Region $region
 
# Check if any instances with the specified name were found
if ($instances. Count -gt 0) {
 $message = @{Status ="Succeeded"; Message = "EC2 instance was found"}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message})
$stopRetry = $true
} else {
     $message = @{Status ="Failed"; Message ="EC2 instance wasn't found."}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message})
 
     $stopRetry = $true
}
}
catch {
        if ($retryCount -gt 3){
 
                $message = @{Status ="Failed"; Message ="EC2 instance wasn't found"}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message})
 
                $stopRetry = $true
            }
        else {
                
                Write-Host "Tried validating three times and the EC2 instance does not exist."
                
                Start-Sleep -Seconds 60
 
                $Retrycount = $Retrycount + 1
            }
       
    }
}while ($stopRetry -eq $false) {
   
}

PowerShell based Validations using APIs

CloudLabs supports PowerShell-based validations using APIs. Below are the instructions on how to create a PowerShell based Validation using APIs.

  1. Follow Steps 1 to 8 of the above section, How to Configure Validations to create a Validation Step. Once you are in the Add Step window, follow the next steps to configure a PowerShell based validations using APIs.

  2. A script can be configured as follows:

    • Name: Validate Virtual Machine (Enter a name of your preference, This is will appear in the lab details page of the user)

    • Validation Type: Custom

    • Score: 0 (Enter a value of your preference)

    • Script Type: PowerShellV2

    • Script: Sample script will be provided below

    • Parameters: List of Supported Parameters will be given below

    • Run As: System

  1. After entering the required details, click on Submit

  2. Below provided is a sample PowerShell script which calls the Azure API and checks whether a VM is created in the subscription.

$stopRetry = $false
[int]$retryCount = "3"
do{
try {
Set-AzContext -Subscription $SubscriptionId
$token = (Get-AzAccessToken).Token
$headers = @{Authorization="Bearer $token"}

$vmName = "VM"  + $deploymentId
$uri = "https://management.azure.com//subscriptions/" + $SubscriptionId + "/resourceGroups/" + $rg + "/providers/Microsoft.Compute/virtualMachines/" + $vmName + "?api-version=2021-04-01"
$call = (Invoke-WebRequest -Method GET -Headers $headers -Uri $uri).StatusCode
 
if ($call -eq 200)
{
 $message = @{Status ="Succeeded"; Message ="VM01 exists in $rg resource group"}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message})
$stopRetry = $true
}
else {
     $message = @{Status ="Failed"; Message ="VM01 not found in $rg resource group"}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message})
 
     $stopRetry = $true
}
}
catch {
        if ($retryCount -gt 3){
 
                $message = @{Status ="Failed"; Message ="VM not found in $rg resource group"}| ConvertTo-Json

                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{

                                StatusCode = [System.Net.HttpStatusCode]::OK

                                Body = $message})
 
                $stopRetry = $true
            }
        else {
                
                Write-Host "Tried validating three times and the VM does not exist."
                
                Start-Sleep -Seconds 60

                $Retrycount = $Retrycount + 1
            }
       
    }
}while ($stopRetry -eq $false) {
   
}

NOTE: You don't have to handle the authentication part in your PowerShell scripts for validations because the authentication script for Azure/AWS will be automatically appended to the beginning of your PowerShell script when you click the Deploy button.

Deploying the PowerShell Validations

Once you have configured the lab validation steps, click on DEPLOY ALL STEPS (1) button in the Course Details tab of the template and wait for 5-7 minutes for the validation steps to be mapped to the appropriate lab.

NOTE: Once you have clicked on DEPLOY ALL STEPS, reach back to us with the template details, we will be performing the manual steps from the backend.

Best Practices to follow while authoring PowerShell based validations

  1. While writing the conditions for if else statement please follow the below pattern for writing output messages.

$message = @{Status ="Succeeded"; Message ="<your message here>"}| ConvertTo-Json
 
                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
 
                                StatusCode = [System.Net.HttpStatusCode]::OK
 
                                Body = $message
  1. Make sure that no resource names or subscription properties are hardcoded.

  2. While authoring the PowerShell script make sure to use the try/catch method just like the script provided below.

# Get EC2 instances with the specified name
do{
    try
     {
$instances = Get-EC2Instance -Region $region

# Check if any instances with the specified name were found
if ($instances. Count -gt 0) {
     $message = @{Status ="Succeeded"; Message = "EC2 instance was found"}| ConvertTo-Json 

                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{

                                StatusCode = [System.Net.HttpStatusCode]::OK

                                Body = $message})
} else {
     $message = @{Status ="Failed"; Message ="EC2 instance wasn't found."}| ConvertTo-Json

                Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{

                                StatusCode = [System.Net.HttpStatusCode]::OK

                                Body = $message})

     break 
}
}
    catch {
        if ($retryCount -gt 3){
                Write-host "not onboarded"
                $stopRetry = $true
            }
        else {
                Write-host "trying to validate one more time"
                Start-Sleep -Seconds 60
                $Retrycount = $Retrycount + 1
            }
       
    }
}while ($stopRetry -eq $false) 

Parameters

CloudLabs supports a set of parameters that can be used while authoring a PowerShell-based Validation. What a parameter essentially does is fetch a real-time value and pass it to the PowerShell script. For example, the GET-DEPLOYMENT-ID parameter retrieves the Deployment ID for the user context in which the script execution is taking place and passes that value to the script. Let’s have a look at another example. Have a look at the below image of three parameters defined in a PowerShell script-based validation.

In the example above, the lab author has defined a variable named $SubscriptionId in the PowerShell script. The author utilized the CloudLabs parameter GET-SUBSCRIPTION to retrieve the subscription ID and then passed it to the PowerShell script to store it in the variable $SubscriptionId

In addition to the System Supported parameters, we can pass the Output parameters of the template that is being used. Have a look at the case below.

In the above example, the LABVMNAME is the Output parameter of the Azure ARM Template. What CloudLabs will do is that, the value corresponding to the Output parameter LABVMNAME will be fetched and passed on to the PowerShell variable vmName which is defined in the PowerShell script. Now the lab author can use the value fetched from the ARM template in the PowerShell validation.

Parameters that can be passed

Below provided are the Parameters that can be passed on to a PowerShell based validation in CloudLabs.

Parameter

Remarks

GET-AZUSER-UPN

Gets user email (Works for both Azure and AWS)

GET-AZUSER-PASSWORD

Gets user Password (Works for both Azure and AWS)

GET-DEPLOYMENT-ID

Gets CloudLabs deployment Id

GET-RG-customsuffix-NAME

Gets the Resource Group Names

GET-SUBSCRIPTION

Gets the Subscription (Works for both Azure and AWS, Fetches Account ID for AWS)

GEN-PASSWORD

Generates a random password of 12 characters

GEN-UNIQUE

Generates a GUID of 18 characters starting with 'cs'

GEN-UNIQUE-NUM-[Limit]

Generates a random number with upper limit [Limit]

GEN-SSH-PUB-KEY

Generates SSH Public Key

GEN-GUID

Generates a GUID

CONFIG_STORAGE_ACCOUNT_NAME

Gets Azure Functions storage account name

GET-SERVICEPRINCIPAL-NAME

Gets Service Principal display name

GET-SERVICEPRINCIPAL-SECRET

Gets Service Principal secret key for Azure (Works for AWS by fetching Access Key Secret)

GET-SERVICEPRINCIPAL-APPLICATION-ID

Gets Service Principal Application Id (Works for AWS by fetching Access Key)

GET-SERVICEPRINCIPAL-OBJECT-ID

Gets Service Principal Application Object Id (Works for AWS by fetching Access Key)

GET-SERVICEPRINCIPAL-SPOBJECT-ID

Gets Service Principal Object Id

GET-PARAMETER-FILE-BASEURI

Gets Parameter file base URI

GET-TEMPLATE-FILE-BASEURI

Gets Template file base URI

GET-AZUSER-OBJECTID

Gets Azure AD user object Id

GET-TENANT-FQDN

Gets Azure AD domain

GET-ODL-ID

Get the On-Demand Lab ID

GET-LAUNCH-TYPE

Returns the purpose of deployment from CloudLabs. This can be hands-on lab, template/subscription validation and other types of deployments.

GET-TEMPLATE-ID

Gets the ID of the CloudLabs Template

GET-TENANT-ID

Gets the CloudLabs Tenant ID