Azure Automations - Can we pass parameters from a powershell main runbook to a python child - azure

I'm facing an issue for which i have not found the solution.
I trying to execute a python runbook from my parent which is in powershell.
The list of commands i tried in my powershell runbook :
Start-AzureRmAutomationRunbook -ResourceGroupName "" -AutomationAccountName "" -Name "" -Parameters $params
Start-AutomationRunbook -Name "" -Parameters $params
Start-AzAutomationRunbook -ResourceGroupName "" -AutomationAccountName "" -Name "" - Parameters $params
Here is my variable params :
$params = #{"args"="Hello"}
If anyone has the solution I'll be grateful ! I tried all day without success.
Thank you in advance for your help

The -Parameters option doesn't work for Python runbooks . You can use the -Parameters option of Start-AutomationRunbook from inside another runbook.
The workaround is to use the internal Automation module Start-AutomationRunbook instead of the external Start-AzureRmAutomation module.
Create a new runbook named Start-PythonRunbook as follow :
Param(
[parameter(Mandatory=$true)] [string]$runbook,
[string]$args
)
Start-AutomationRunbook -Name $runbook -Parameters $args
Now you can start this runbook using the Start-AzureRmAutomationRunbook cmdlet :
Start-AzureRmAutomationRunbook -ResourceGroupName <RGName>
-AutomationAccountName <AAName>
-Name Start-PythonRunbook `
-Parameters #{ "runbook" = "<pythonrunbookname>"; "args" = "arg1 arg2 arg3 arg4 arg5 arg6" }
You can check this GitHub discussion for more information.

Related

Assign the result of a query to a variable in powershell in Azure-Runbooks

I have a runbook using automation in Azure. It is getting a single integer result from a table and it can return the correct value. The code I am using is below and it works.
$SQLServerCred = Get-AutomationPSCredential -Name "SqlCredential"
#Import the SQL Server Name from the Automation variable.
$SQL_Server_Name = Get-AutomationVariable -Name "SqlServer"
#Import the SQL DB from the Automation variable.
$SQL_DB_Name = Get-AutomationVariable -Name "Database"
$Query = "select max(je.ExecutionOrder) as LastStepExecuted
from PPoint.JobExecutionHistory je
where je.EventType = 'Start'
and je.JobRunId = PPoint.fnGetJobRunID()"
invoke-sqlcmd -ServerInstance "$SQL_Server_Name" -Database "$SQL_DB_Name" -Credential $SQLServerCred -Query "$Query" -Encrypt
The next step for me is to assign the result from the query to a variable and then evaluate it to see if it should call another runbook. So I want to have a variable named LastStep and assign it the integer result of LastStepExecuted from the query below. I then want to do something along this line (this is pseudocode)
if LastStep = 2147483647
call another runbook
else
do nothing - end the runbook
I have tried several ways to capture the LastStepExecuted in a variable but I can't figure it out. Can anyone help?
Any help or advice much appreciated.
You can use the Start-AzAutomationRunbook cmdlet to trigger a child runbook from the another run book inside the automation account.
$SQLServerCred = Get-AutomationPSCredential -Name "SqlCredential"
#Import the SQL Server Name from the Automation variable.
$SQL_Server_Name = Get-AutomationVariable -Name "SqlServer"
#Import the SQL DB from the Automation variable.
$SQL_DB_Name = Get-AutomationVariable -Name "Database"
$Query = "select max(je.ExecutionOrder) as LastStepExecuted
from PPoint.JobExecutionHistory je
where je.EventType = 'Start'
and je.JobRunId = PPoint.fnGetJobRunID()"
$LastStep=invoke-sqlcmd -ServerInstance "$SQL_Server_Name" -Database "$SQL_DB_Name" -Credential $SQLServerCred -Query "$Query" -Encrypt
if($LastStep -eq 2147483647)
{
Start-AzAutomationRunbook -AutomationAccountName "MyAutomationAccount" -Name "Test-ChildRunbook" -ResourceGroupName "LabRG" -DefaultProfile $AzureContext -Parameters $params -Wait
}
else
{
Write-Output "conditionfailed the value of $LastStep"
}
You can refer this documentation, about modular runbooks in azure automation.

Azure ARM template script error when creating certificate for apex domain

Really scratching my head on this one, I keep getting the error below:
New-AzureRmResourceGroupDeployment : A parameter cannot be found that matches parameter name 'SubjectName'.
At azure_cli_-_create_cert.ps1:12 char:80
for the Azure ARM template script below:
$subscription = ""
$resourceGroupName = ""
$appServicePlanName = ""
$subjectName = ""
Set-AzureRmContext -SubscriptionId $subscription
$appServicePlan = Get-AzureRmResource `
| Where-Object {$_.ResourceGroupName -eq $resourceGroupName} `
| Where-Object {$_.Name -eq $appServicePlanName}
New-AzureRMResourceGroupDeployment -ResourceGroupName $resourceGroupName -SubjectName $subjectName -AppServicePlanName $appServicePlanName -Location $appServicePlan.Location -TemplateFile "CreateHttpFreeCert.json"
Does anyone know why this is?
I am running the script in a windows powershell script (i.e. .ps1 script).
It seems like you need to supply the parameters for your template in as a JSON file using -TemplateParameterFile or -TemplateParameterObject
https://learn.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermresourcegroupdeployment?view=azurermps-6.13.0#example-1--use-a-custom-template-and-parameter-file-to-create-a-deployment

How can I simply get the powerstate from within a powershell workflow automation runbook in Azure?

I have a Powershell workflow runbook that automates starting and shutting down VMs in Azure, I updated the modules in an automation account (so I could use it for other things) and it has stopped the script working. I have fixed most of the broken stuff but the bit that is not now working is obtaining the power state eg: PowerState/deallocated so that it can be shutdown/started up. Here is my code:
$vmFullStatus = Get-AzureRmVM -ResourceGroupName test1 -Name test1 -Status
$vmStatusJson = $vmFullStatus | ConvertTo-Json -depth 100
$vmStatus = $vmStatusJson | ConvertFrom-Json
$vmStatusCode = $vmStatus.Statuses[1].code
Write-Output " VM Status Code: $vmStatusCode"
The Write-Output VM Status Code is now blank in the output of the runbook, but it outputs fine in standard shell. I only have limited experiences in workflow runbooks but I believe it needs to be converted to Json so the Workflow can use it.
I think the issue may lie with the statuses as when it is converted to Json it displays:
"Statuses": [
"Microsoft.Azure.Management.Compute.Models.InstanceViewStatus",
"Microsoft.Azure.Management.Compute.Models.InstanceViewStatus"
],
Which doesn't now show the PowerState. How can I get the powerstate of a vm from within a powershell workflow runbook so it can used? Thanks
I have tried an inline script and it does work if you specify a vm name:
$vmStatusCode = InlineScript {
$vmFullStatus = Get-AzureRmVM -ResourceGroupName test1 -Name test1 -Status
$vmStatusJson = $vmFullStatus | ConvertTo-Json -depth 100
$vmStatus = $vmStatusJson | ConvertFrom-Json
$vmStatus.Statuses[1].code
}
But it doesn't work when you pass variables:
$vmFullStatus = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status
Get-AzureRmVM : Cannot validate argument on parameter 'ResourceGroupName'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
it needs to be run without an inline script - any ideas?
forgot to add $using:
$vmStatusCode = InlineScript {
$vmFullStatus = Get-AzureRmVM -ResourceGroupName $using:vm.ResourceGroupName -Name $using:vm.Name -Status
$vmStatusJson = $vmFullStatus | ConvertTo-Json -depth 100
$vmStatus = $vmStatusJson | ConvertFrom-Json
$vmStatus.Statuses[1].code
}
This now works!

Using Service Bus Queue InputObject Parameter on Powershell

I have a Azure Service Bus Namespace which has hundreds of queues and I need to Set the MaximumDeliveryCount to 1 instead of a default value of 10. Doing it manually on portal will obviously take time. So I want to do it through PowerShell Script.
Not sure what should be the -InputObject Parameter. The Microsoft article Set-AzServiceBusQueue says that the InputObject Type is of PSQueueAttributes given here PSQueueAttributes Class
I tried entering 'MaxDeliveryCount' attribute but receiving this error:
Set-AzServiceBusQueue : Cannot bind parameter 'InputObject'. Cannot convert the "MaxDeliveryCount" value of type "System.String" to type
"Microsoft.Azure.Commands.ServiceBus.Models.PSQueueAttributes".
At line:7 char:121
+ ... $Servicebus_namespace -Name $_ -InputObject MaxDeliveryCount -WhatIf
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-AzServiceBusQueue], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.ServiceBus.Commands.Queue.SetAzureRmServiceBusQueue
Here is the code:
$Servicebus_queue = (Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace).Name
$Servicebus_queue
$Servicebus_queue.foreach{
$Servicebus_queue = (Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace)
$Servicebus_queue.MaxDeliveryCount = 1
Set-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace -Name $_ -InputObject MaxDeliveryCount
}
I've researched everywhere but could not find any solution. Also the above links route to AzureRM module for Set-AzServiceBusQueue command.
Appreciate if anyone can help.
As per my comment, you need to pass a queue object (i.e. a PSQueueAttributes instance) into Set-AzServiceBusQueue, but you've also got something slightly screwy going on with your variable assignments and your foreach.
The sample below should hopefully help straighten things out...
# get a queue (or an array of queues). remove the ().Name as this just extracts
# their names and we really want the whole queue object. also, pluralise the
# variable name so it doesn't collide with our loop variables
$Servicebus_queues = Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace
$Servicebus_queues.foreach{
# get a reference to the current ppieline variable
# see https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-6#_
$Servicebus_queue = $_
$Servicebus_queue.MaxDeliveryCount = 1
# -InputObject needs to be a queue (i.e. a PSQueueAttributes instance)
Set-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace -Name $_ -InputObject $Servicebus_queue
}
According to my research, If you want to use the parameter InputObject, you can must provide PSQueueAttributes as its value.
For example :
$Servicebus_queue = (Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace)
$Servicebus_queue.MaxDeliveryCount = 1
Set-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace -Name $_ -InputObject $Servicebus_queue
For more details, please refer to the document.
Update
If you want to update Service Bus Queue with PowerShell, please refer to the following script
Connect-AzAccount
$ResourceGroupName=" "
$Namespace=" "
$queues = Get-AzServiceBusQueue -ResourceGroupName $ResourceGroupName -Namespace $Namespace
foreach($queue in $queues){
$queue.MaxDeliveryCount = 1
Set-AzServiceBusQueue -ResourceGroup $ResourceGroupName -NamespaceName $Namespace -QueueName $queue.Name -QueueObj $queue
}

How do I translate a set of powershell commands into a script that I can run when I want?

I have a set of commands I can use in azure powershell. The commands create a resource group, app service, etc. I want to bundle them up so that I can just type one command into a terminal and run all of the deployment in one go.
# Ask user for work item id
$workItemId = Read-Host -Prompt "Enter the Work Item ID"
# Set Variables
$appdirectory="C:\Users\Charles\Desktop\Timesheet App\Discover\Client\build"
$webappname="discoverTest$workItemId"
$location="West Europe"
# Create a resource group.
New-AzResourceGroup -Name discoverTest$workItemId -Location $location
# Create an App Service plan in `Free` tier.
New-AzAppServicePlan -Name $webappname -Location $location `
-ResourceGroupName discoverTest$workItemId -Tier Free
# Create a web app.
New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname `
-ResourceGroupName discoverTest$workItemId
# Get publishing profile for the web app
$xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname `
-ResourceGroupName discoverTest$workItemId `
-OutputFile null)
# Extract connection information from publishing profile
$username = $xml.SelectNodes("//publishProfile[#publishMethod=`"FTP`"]/#userName").value
$password = $xml.SelectNodes("//publishProfile[#publishMethod=`"FTP`"]/#userPWD").value
$url = $xml.SelectNodes("//publishProfile[#publishMethod=`"FTP`"]/#publishUrl").value
# Upload files recursively
Set-Location $appdirectory
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$files = Get-ChildItem -Path $appdirectory -Recurse #Removed IsContainer condition
foreach ($file in $files)
{
$relativepath = (Resolve-Path -Path $file.FullName -Relative).Replace(".\", "").Replace('\', '/')
$uri = New-Object System.Uri("$url/$relativepath")
if($file.PSIsContainer)
{
$uri.AbsolutePath + "is Directory"
$ftprequest = [System.Net.FtpWebRequest]::Create($uri);
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
$ftprequest.UseBinary = $true
$ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$response = $ftprequest.GetResponse();
$response.StatusDescription
continue
}
"Uploading to " + $uri.AbsoluteUri + " from "+ $file.FullName
$webclient.UploadFile($uri, $file.FullName)
}
$webclient.Dispose()
$workItemId = Read-Host -Prompt "Enter the Work Item ID"
Remove-AzResourceGroup -Name "discoverTest$workItemId" -Force
# print variable
Write-Host $variable
I want to be able to run a single command and have the full deployment process executed.
There are two ways to realize your needs, as below.
Extract all parameters you used in these PowerShell command lines as the arguments for a PowerShell Script <your-script-name>.ps1 which includes all same commands as yours. Please refer to the existing SO thread How to handle command-line arguments in PowerShell to know how to do. Then, you just need to run <your-script-name>.ps1 with these arguments in a terminal which had pre-installed Azure PowerShell Module.
Follow the blog Four ways to package a non-GUI PowerShell script as an executable file to make an executable file with the current set of commands.
Normally, I think the first way is better and be recommended.

Resources