I use a library of Powershell functions frequently in my Morpheus Tasks. I decided to build these into a script and store it on Github. For convenience I developed a Powershell function which you can add to your Morpheus Powershell tasks. The function takes a raw Url from Github and loads the Powershell into a Dynamic Module which then gives the Morpheus Task access to the library of Powershell functions.
Follow the example below to try this for yourself.
Create a Powershell Task type, set the Execute Target as Resource. and add this function into the Task script
# Declare the function - this will be standard in all Tasks
Function New-ModulefromGitHub {
<#
.SYNOPSIS
Takes a Github Raw url, downloads the Powershell Script and Executes as a Dynamic Module
.DESCRIPTION
Takes a Github Raw url, downloads the Powershell Script and Executes as a Dynamic Module
Examples:
New-ModulefromGitHub -ScriptUrl <Github Raw URL for the Powershell script> -Name "GibModule"
.PARAMETER ScriptUrl
GitHub Raw Url to Powershell script
.PARAMETER Name
A String to identify the Dynamic Module name
.OUTPUTS
Loads a Dynamic Module
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true,Position=0)]
[String]$ScriptUrl,
[Parameter(Mandatory=$true,Position=1)]
[String]$Name
)
if ($ScriptUrl) {
try {
$Response = Invoke-WebRequest -Uri $ScriptUrl -UseBasicParsing -ErrorAction SilentlyContinue
$StatusCode = $Response.StatusCode
}
catch {
$StatusCode = $_.Exception.Response.StatusCode
Write-Warning "Cannot locate Script Url $ScriptUrl - Status:$StatusCode"
}
if ($StatusCode -eq 200) {
try {
New-Module -Name $Name -ScriptBlock ([ScriptBlock]::Create($Response.Content))
}
catch {
Write-Error "ScriptUrl is not a valid Powershell Module ScriptBlock"
}
}
} else {
Write-Warning "You must enter a Script URL"
}
}
# Start your custom script here
# Git Raw URL of a scipt to load as a Module. (Note it must be a raw Url type)
$GitUrl = "https://raw.githubusercontent.com/spottsmorpheus/invokePSTask/main/Examples/moduleExample.ps1"
# Hide Progress updates in Morpheus
$ProgressPreference="SilentlyContinue"
# Load the Dynamic Module using the function created above. To prevent output being written into the
# script assign the command below into a variable eg $NoOutput = New-ModuleFromGitHub ...
New-ModuleFromGitHub -ScriptUrl $GitUrl -Name "Git-Test"
#Fuctions are now available - use them as you normally would. You may access Morpheus Variables
$Inst = "<%=instance.name%>"
#Call a Function defined in the Module - here you can pass in any Morpheus Variables
$Status = Get-InstanceInfo -Instance $Inst
$Status | ConvertTo-Json -Depth 3
#End of Task
Execute the task against an Instance type. It should generate output as so
Steve Potts
Morpheus Support EMEA