Get job status in Azure Runbook - powershell

I would like to have a runbook run on a schedule but exit if the last job hasn't finished running (i.e. if the schedule is every 2 hours and a job takes 2.5 hours then the next job shouldn't run).
I've tried to use Get-AzureAutomationJob to get the last job status (https://azure.microsoft.com/en-gb/documentation/articles/automation-runbook-execution/#retrieving-job-status-using-windows-powershell), but I can't get it to work. I presume all the preamble to get the subscription etc is required.
"Get-AzureAutomationJob : The Automation account was not found."
$ConnectionAssetName = "AzureClassicRunAsConnection"
# Get the connection
$connection = Get-AutomationConnection -Name $connectionAssetName
# Authenticate to Azure with certificate
Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
if ($Conn -eq $null)
{
throw "Could not retrieve connection asset: $ConnectionAssetName. Assure that this asset exists in the Automation account."
}
$CertificateAssetName = $Conn.CertificateAssetName
Write-Verbose "Getting the certificate: $CertificateAssetName" -Verbose
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
if ($AzureCert -eq $null)
{
throw "Could not retrieve certificate asset: $CertificateAssetName. Assure that this asset exists in the Automation account."
}
Write-Verbose "Authenticating to Azure with certificate." -Verbose
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName - SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
$job = (Get-AzureAutomationJob –AutomationAccountName "THE NAME OF THE AUTOMATION ACCOUNT AS IT APPEARS IN THE PORTAL" –Name "JobStatusTest" | sort LastModifiedDate –desc)[0]

Well, you would need to use Get-AzureRMAutomation job for that. Let me elaborate on that, I think in march 2016 Microsoft removed Azure Automation from the OLD azure model and now it is present only in the new one. so you would need to add RM to your commandlets

Related

Azure Runbook Error, AzureRmStorageAccountKey Cannot Index into null array

I am trying to run this command within an Azure Run book
(Get-AzureRmStorageAccountKey -Name $defaultStorageAccountName -ResourceGroupName $defaultResourceGroupName).Value[0]
It runs fine on my local machine and I can see the Storage Account Key. However, when I run the same command in Azure Runbook it throws the following error
Cannot index into a null array
If I just run Get-AzureRmStorageAccountKey -Name $defaultStorageAccountName -ResourceGroupName $defaultResourceGroupName in the Azure Runbook, it runs fine and I can see the Keys. It is just when I am selecting an element from an Array that it fails and throws an error.
The PowerShell version is 5 on my local machine and on Azure Runbook.
Update:
My issue was resolved after updating the Modules from the Gallery in my automation account.
According to your description, I test your cmdlets in my runbook, I could get storage key.
You could use the following commands to login your subscriptions.
Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$connectionName = Get-AutomationConnection -Name "AzureRunAsConnection"
$AzureCredentialAssetName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $AzureCredentialAssetName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$key=(Get-AzureRmStorageAccountKey -Name <storage account name> -ResourceGroupName <resource group name>).Value[0]
"The storage account key is $key"
More information please refer to this link.
Update
You need update Azure Storage account module version in automation account, then you could solve this issue.

Azure Runbook : What credential to use?

I'm trying to create a runbook to restart my web app. I'm new to this so I created a credential in the automation blade but I don't know what is the username/pwd is supposed to be? Is it the same with my azure login account?
Tried that and obviously when I test the runbook this error shows up :
Add-AzureAccount : unknown_user_type: Unknown User Type
At RestartJob:13 char:13
+ + CategoryInfo : CloseError: (:) [Add-AzureAccount],
AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.AddAzureAccount
Been trying to figure this out on msdn as well.. any help?
According to your description, I test in my lab. The fowwling cmdlets work for me.
$ConnectionAssetName = "shuitest"
# Get the connection
$connection = Get-AutomationConnection -Name $connectionAssetName
# Authenticate to Azure with certificate
Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
if ($Conn -eq $null)
{
throw "Could not retrieve connection asset: $ConnectionAssetName. Assure that this asset exists in the Automation account."
}
$CertificateAssetName = $Conn.CertificateAssetName
Write-Verbose "Getting the certificate: $CertificateAssetName" -Verbose
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
if ($AzureCert -eq $null)
{
throw "Could not retrieve certificate asset: $CertificateAssetName. Assure that this asset exists in the Automation account."
}
Write-Verbose "Authenticating to Azure with certificate." -Verbose
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
Before you execute the runbook, you should create AssetName and Certificate on Azure Portal.
1.Certificate assets in Azure Automation
Please select your runbook-->ASSETS--Certificate.
2.Create Connection(AssetName). Please select your runbook-->ASSETS--Connections. According to your scenario, you should select AzureClassicCertificate

Visual Studio Team Services release issue

When I try to create a release within Visual Studio, I run into this error
azure deployment
Given that I have full permissions on my Azure account and I have no issues logging into my azure session
I think this is a bug within VSTS, the questions are, how to tweak this situation? can I use the Release management tool for visual studio 2013 temporary until I find out how to do a release
Rem: I tried the old method which uses powershell to get info about principal id, tenant id and so on but this method needs that my app has to be backed by AAD which is not the case for our situation and second this method is supposed deprecated for now
Any help will be highly appreciated
Thank you
It is working fine for me. (Success configuring Azure service connection by clicking Authorize button).
You can clear Internet browser cache, then Start InPrivate Browsing, you can try it in other machine.
》I tried the old method which uses powershell to get info about principal id, tenant id and so on but this method needs that my app has to be backed by AAD which is not the case for our situation
You don’t need to configure app that backed by ADD manually, just need to run this PowerShell script directly (refer to this article)
param
(
[Parameter(Mandatory=$true, HelpMessage="Enter Azure Subscription name. You need to be Subscription Admin to execute the script")]
[string] $subscriptionName,
[Parameter(Mandatory=$true, HelpMessage="Provide a password for SPN application that you would create")]
[string] $password,
[Parameter(Mandatory=$false, HelpMessage="Provide a SPN role assignment")]
[string] $spnRole = "owner"
)
#Initialize
$ErrorActionPreference = "Stop"
$VerbosePreference = "SilentlyContinue"
$userName = $env:USERNAME
$newguid = [guid]::NewGuid()
$displayName = [String]::Format("VSO.{0}.{1}", $userName, $newguid)
$homePage = "http://" + $displayName
$identifierUri = $homePage
#Initialize subscription
$isAzureModulePresent = Get-Module -Name AzureRM* -ListAvailable
if ([String]::IsNullOrEmpty($isAzureModulePresent) -eq $true)
{
Write-Output "Script requires AzureRM modules to be present. Obtain AzureRM from https://github.com/Azure/azure-powershell/releases. Please refer https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/DeployAzureResourceGroup/README.md for recommended AzureRM versions." -Verbose
return
}
Import-Module -Name AzureRM.Profile
Write-Output "Provide your credentials to access Azure subscription $subscriptionName" -Verbose
Login-AzureRmAccount -SubscriptionName $subscriptionName
$azureSubscription = Get-AzureRmSubscription -SubscriptionName $subscriptionName
$connectionName = $azureSubscription.SubscriptionName
$tenantId = $azureSubscription.TenantId
$id = $azureSubscription.SubscriptionId
#Create a new AD Application
Write-Output "Creating a new Application in AAD (App URI - $identifierUri)" -Verbose
$azureAdApplication = New-AzureRmADApplication -DisplayName $displayName -HomePage $homePage -IdentifierUris $identifierUri -Password $password -Verbose
$appId = $azureAdApplication.ApplicationId
Write-Output "Azure AAD Application creation completed successfully (Application Id: $appId)" -Verbose
#Create new SPN
Write-Output "Creating a new SPN" -Verbose
$spn = New-AzureRmADServicePrincipal -ApplicationId $appId
$spnName = $spn.ServicePrincipalName
Write-Output "SPN creation completed successfully (SPN Name: $spnName)" -Verbose
#Assign role to SPN
Write-Output "Waiting for SPN creation to reflect in Directory before Role assignment"
Start-Sleep 20
Write-Output "Assigning role ($spnRole) to SPN App ($appId)" -Verbose
New-AzureRmRoleAssignment -RoleDefinitionName $spnRole -ServicePrincipalName $appId
Write-Output "SPN role assignment completed successfully" -Verbose
#Print the values
Write-Output "`nCopy and Paste below values for Service Connection" -Verbose
Write-Output "***************************************************************************"
Write-Output "Connection Name: $connectionName(SPN)"
Write-Output "Subscription Id: $id"
Write-Output "Subscription Name: $connectionName"
Write-Output "Service Principal Id: $appId"
Write-Output "Service Principal key: <Password that you typed in>"
Write-Output "Tenant Id: $tenantId"
Write-Output "***************************************************************************"

Get-AzureVM returning null despite having VMs under the subscription

I was working on a script which I have downloaded from the gallery to stop all VMs running in a subscription. This was running perfectly until last week, but when I ran it yesterday, it couldnt find any VM in my subscription (VMs are there in my sub and running). Script is below:
workflow Stop-AllAzureVM
{
# Add the credential used to authenticate to Azure.
# TODO: Fill in the -Name parameter with the Name of the Automation PSCredential asset
# that has access to your Azure subscription. "myPScredName" is your asset name that reflects an OrgID user
# like "someuser#somewhere.onmicrosoft.com" that has Co-Admin rights to your subscription.
$Cred = Get-AutomationPSCredential -Name "myPsCred"
# Connect to Azure
Add-AzureAccount -Credential $Cred
# Select the Azure subscription you want to work against
# TODO: Fill in the -SubscriptionName parameter with the name of your Azure subscription
Select-AzureSubscription -SubscriptionName "MySubs"
# Get all Azure VMs in the subscription that are not stopped and deallocated, and shut them down
# all at once.
$VMs = Get-AzureVM | where-object -FilterScript {$_.status -ne 'StoppedDeallocated'}
if (!$VMs)
{
Write-Output "No VM running at the moment"
}
else
{
Write-Output "VM(s) found running, proceeding for shutdown"
}
foreach -parallel ($vm in $VMs)
{
$stopRtn = Stop-AzureVM -Name $VM.Name -ServiceName $VM.ServiceName -force -ea SilentlyContinue
$count=1
if(($stopRtn.OperationStatus) -ne 'Succeeded')
{
do{
Write-Output "Failed to stop $($VM.Name). Retrying in 60 seconds..."
sleep 60
$stopRtn = Stop-AzureVM -Name $VM.Name -ServiceName $VM.ServiceName -force -ea SilentlyContinue
$count++
}
while(($stopRtn.OperationStatus) -ne 'Succeeded' -and $count -lt 5)
}
if($stopRtn){Write-Output "Stop-AzureVM cmdlet for $($VM.Name) $($stopRtn.OperationStatus) on attempt number $count of 5."}
}
}
This script always prints "No VM running at the moment"
I tried Get-AzureVM without any condition also but the result was same.
I am not sure if something has changed in past couple of weeks which is resulting in this issue.
Update-1:
I tried adding below commands in script:
$VMs = Get-AzureVM
$subscriptions = Get-AzureSubscription
Write-Output "Found [$($subscriptions.Count)] subscriptions accessible to user"
Write-Output "Found [$($VMs.Count)] VMs in Subscription"
and I got below output:
Found [] subscriptions accessible to user
Found [0] VMs in Subscription
No VM running at the moment
So it looks like something weird had happened in my automation account and I dont seem to have any clue about it!
To all who are facing this issue, not sure if this is the right way to fix this but at least as a workaround, I tried creating a new automation account and copy pasted same runbook in it and it is working fine for me.

Azure deployment script keeps complaining "CurrentStorageAccount is not set"

I want to do automated deployment with Bamboo (a Continuous Integration solution). I found in here(http://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/#script) a piece of script to help. The main code snippet:
#configure powershell with Azure 1.7 modules
Import-Module Azure
#configure powershell with publishsettings for your subscription
$pubsettings = $subscriptionDataFile
Import-AzurePublishSettingsFile $pubsettings
Set-AzureSubscription -CurrentStorageAccount $storageAccountName -SubscriptionName $selectedsubscription
write-host $storageAccountName
write-host "$selectedsubscription"
#set remaining environment variables for Azure cmdlets
$subscription = Get-AzureSubscription $selectedsubscription
$subscriptionname = $subscription.subscriptionname
$subscriptionid = $subscription.subscriptionid
$slot = $environment
#main driver - publish & write progress to activity log
Write-Output "$(Get-Date –f $timeStampFormat) - Azure Cloud Service deploy script started."
Write-Output "$(Get-Date –f $timeStampFormat) - Preparing deployment of $deploymentLabel for $subscriptionname with Subscription ID $subscriptionid."
Publish
$deployment = Get-AzureDeployment -slot $slot -serviceName $servicename
$deploymentUrl = $deployment.Url
Write-Output "$(Get-Date –f $timeStampFormat) - Created Cloud Service with URL $deploymentUrl."
Write-Output "$(Get-Date –f $timeStampFormat) - Azure Cloud Service deploy script finished."
I just first tried running this script from cmd by executing powershell E:\CI\OCZDeployment\publish_cloud_service.ps1 -environment Staging -serviceName "ocz" -storageAccountName "t2vsoft" -packageLocation OCZ.cspkg -cloudConfigLocation ServiceConfiguration.Cloud.cscfg -subscriptionDataFile E:\CI\OCZDeployment\SubscriptionDataFile.publishsettings -selectedsubscription "Development Subscription"
, where the publishsettings file is downloaded from Azure.
But I kept getting the error message:
New-AzureDeployment : CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.
It has definitely been set in the snippet. I even tried copy & paste the Set-AzureSubscription line to inside New-AzureDeployment function. No luck.
Help me! Thank you!
Fixed. Don't know what was exactly the cause but i removed all registered azure subscriptions by executing:
PS> Get-AzureSubscription | ForEach-Object { Remove-AzureSubscription $_.SubscriptionName }
and re-imported the subscription by executing:
PS> Import-AzurePublishSettingsFile xxx.publishsettings
and it all worked! :)
There really were some similarly-named subscriptions in the subscription list. There might have been conflicts as such the azure scripts didn't know which one they really wanted.
If you have multiple subscriptions then you need to make sure the subscription that you want to use is set to the default. This can be done with the following:
Select-AzureSubscription -SubscriptionName "{subscriptionName}" -Default
if you aren't sure what your subscription name is you can use the following to see all of your subscriptions:
Get-AzureSubscription