Not able to access Azure FileShare Storage container from Azure Automation Runbook - azure

I've the following Azure Automation Runbook script which goal is to take an dump/export from a REST API call which must run from a target device which is able to reach the REST API device. So Azure Automation runbook is targeting a "proxy server" then from this we're taking the REST API backup.
The approach has been working exception the fact we're able not to copy this backup file from the target server once 'cm.vm.run_command' presents output size limitation and is truncating the backup. The workaround we found for this was copying the backup file from the 'target/proxy server' directly into a Storage Account Fileshare which is mounted on the target/proxy server. My problem now is when running from Azure Automation it's not able to access the drive mounted by other user and/or is not able to mount the device or access it directly like below errors messages. Does anybody have any alternative for this ? I was able to check the runbook is having connectivity on the storage account ports 443/445 from t. That was one of the possible reasons described here https://learn.microsoft.com/en-us/azure/storage/files/storage-troubleshoot-windows-file-connection-problems
Below the commands and errors I'm receiving and the whole script used.
Copy-item -Path C:\Devicebackup.txt -Destination \\storage_account_name.file.core.windows.net\configdatafileshare\Orchestration
net use w: \\storage_account_name.file.core.windows.net\configdatafileshare\Orchestration `'/yBapkthow==`' /user:Azure\storage_account_name
Copy-item : The network path was not found
At C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows\1.1.5\Downloads\s
cript9.ps1:15 char:1
+ Copy-item -Path C:\Devicebackup.txt -Destination \\storage_account_name. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Comma
nds.CopyItemCommand
The option /DL2D2QKD1OU2ZKEOJVRK4LGPIRTJKAJBZ+EDKNHWVYYEJDDYSL9CPB5T8F/9VWQBMBWC37B1NJS4YBAPKTHOW== is unknown.
The syntax of this command is:
NET USE
[devicename | *] [\\computername\sharename[\volume] [password | *]]
[/USER:[domainname\]username]
[/USER:[dotted domain name\]username]
[/USER:[username#dotted domain name]
[/SMARTCARD]
[/SAVECRED]
[[/DELETE] | [/PERSISTENT:{YES | NO}]]
NET USE {devicename | *} [password | *] /HOME
NET USE [/PERSISTENT:{YES | NO}]
Param (
[Parameter(Mandatory=$false)][string] $rgName
,[Parameter(Mandatory=$false)][string] $ProxyServerName
)
function CreatePSCommandFile {
Param(
[parameter(Mandatory=$true)][String[]]$DeviceName,
[parameter(Mandatory=$true)][String[]]$DeviceIP,
[parameter(Mandatory=$true)][String[]]$ApiToken
)
$remoteCommand =
#"
add-type #`"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
`"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri 'www.mydownload.com' -UseBasicParsing -Headers #{ Authorization="Bearer $($ApiToken)" } | Out-file C:\Devicebackup.txt
net use w: \\storage_account_name.file.core.windows.net\configdatafileshare\Orchestration `'/STORAGE_KEY+EDknHWvyyeJDDYsL9cPB5T8F/9VwqBmbwc37B1NJS4yBapkthow==`' /user:Azure\storage_account_name
Copy-item -Path C:\Devicebackup.txt -Destination \\storage_account_name.file.core.windows.net\configdatafileshare\Orchestration
"#
Set-Content -Path .\InvokeCommand.ps1 -Value $remoteCommand
}
$connectionName = "AzureRunAsConnection"
try {
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
Write-Host "Logging in to Azure..."
$connectionResult = Connect-AzAccount `
-ServicePrincipal `
-Tenant $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
}
}
function Backup-Device {
Param (
[Parameter(Mandatory=$false)][string] $DeviceName
,[Parameter(Mandatory=$false)][string] $DeviceIP
,[Parameter(Mandatory=$false)][string] $ApiToken
)
# Execute Backup on Fortigate Rest API
CreatePSCommandFile -DeviceName $DeviceName -DeviceIP $DeviceIP -ApiToken $ApiToken
$Output = Invoke-AzVMRunCommand -ResourceGroupName $rgName -VMName $ProxyServerName -CommandId 'RunPowerShellScript' -Scriptpath ".\InvokeCommand.ps1" -Parameter #{'api_url' = "10.29.255.212"; 'api_token' = "0p6h1rmspjf37kp80bc6ny88jw"}
($Output).Value.Message
}
Backup-Device -DeviceName "DeviceName" -DeviceIP '10.29.255.212' -ApiToken 'Api_Token'

Sharing the solution which was presented by a blessed colleague :)
Using New-SmbMapping we were able to mount the Storage Account File Share from Azure Automation PS script successfully.
if (!(Test-Path `$MapDrive)) {
New-SmbMapping -LocalPath `$MapDrive -RemotePath `$RemotePath -UserName `$UserName -Password `$Key
}
Copy-Item .\Devicebackup.txt `$MapDrive

Related

Azure Automation Runbook Workflow looses AzContext

I have written the following runbook workflow, but from time to time I see the error when it try's to start or stop a VM:
Start-AzVM : Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your
Azure credentials.
At StartStopVmByTag:46 char:46
+
+ CategoryInfo : CloseError: (:) [Start-AzVM], ArgumentException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.StartAzureVMCommand
I have tried passing the $azContext variable in, but I still get this issue, how can I further investigate?
workflow StartStopVmByTag {
$connectionName = "AzRunAsConnection2042";
try {
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
Write-Output "Logging in to Azure..."
$null = Add-AzAccount `
-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
}
}
[DateTime]$now = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'GMT Standard Time')
$startTag = 'Start Schedule'
Write-Output "*** $now - Runbook Started ***"
# Get Subscriptions
$Subscriptions = Get-AzSubscription
ForEach ($Subscription in $Subscriptions) {
$azContext = Set-AzContext -SubscriptionId $Subscription.Id
# Get all VM's with a Start or Stop Schedule
Write-Output "$($Subscription.Name): Getting VM's..."
[Array]$taggedVms = Get-AzResource -TagName $startTag -ResourceType 'Microsoft.Compute/virtualMachines'
$taggedVms = $taggedVms | Sort-Object -Property Name -Unique
# For each VM, check if start schedule is valid for now
Foreach -Parallel ($taggedVm in $taggedVms) {
Write-Output "$($Subscription.Name): Found Tagged VM: $($taggedVm.Name), $($startTag): $($taggedVm.Tags.$startTag -replace '\s', '')"
$WORKFLOW:null = Start-AzVM -ResourceGroupName $taggedVm.ResourceGroupName -Name $taggedVm.Name -DefaultProfile $azContext -NoWait
}
}
}
I have been struggling with this issue for a while, and I've tried dozens of different workarounds and nothing has worked. I finally resolved it with these registry settings that force .NET applications to use TLS 1.2. I find it very strange that this solution works, but possibly because the TLS 1.2 set as part of any parent task doesn't get passed on to the job.
They probably aren't all required, but it seems to be a best practice these days anyway.
set-itemproperty "HKLM:\SOFTWARE\Microsoft\.NETFramework\v2.0.50727" -name SystemDefaultTlsVersions -value 1 -Type DWord
set-itemproperty "HKLM:\SOFTWARE\Microsoft\.NETFramework\v4.0.30319" -name SchUseStrongCrypto -value 1 -Type DWord
set-itemproperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727" -name SystemDefaultTlsVersions -value 1 -Type DWord
set-itemproperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319" -name SchUseStrongCrypto -value 1 -Type DWord

Azure Automation Runbook missing mandatory parameters

I'm trying to set a Tag on all virtual machines in my subscription but I keep getting errors when running the Runbook.
The error is the following:
Get-AzureRmVM : Cannot process command because of one or more missing mandatory parameters: ResourceGroupName. At line:30
Here is my Runbook:
$azureConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
#Authenticate
try {
Clear-Variable -Name params -Force -ErrorAction Ignore
$params = #{
ServicePrincipal = $true
Tenant = $azureConnection.TenantID
ApplicationId = $azureConnection.ApplicationID
CertificateThumbprint = $azureConnection.CertificateThumbprint
}
$null = Add-AzureRmAccount #params
}
catch {
$errorMessage = $_
Throw "Unable to authenticate with error: $errorMessage"
}
# Discovery of all Azure VM's in the current subscription.
$azurevms = Get-AzureRmVM | Select-Object -ExpandProperty Name
Write-Host "Discovering Azure VM's in the following subscription $SubscriptionID Please hold...."
Write-Host "The following VM's have been discovered in subscription $SubscriptionID"
$azurevms
foreach ($azurevm in $azurevms) {
Write-Host "Checking for tag $vmtagname on $azurevm"
$tagRGname = Get-AzureRmVM -Name $azurevm | Select-Object -ExpandProperty ResourceGroupName
$tags = (Get-AzureRmResource -ResourceGroupName $tagRGname -Name $azurevm).Tags
If ($tags.UpdateWindow){
Write-Host "$azurevm already has the tag $vmtagname."
}
else
{
Write-Host "Creating Tag $vmtagname and Value $tagvalue for $azurevm"
$tags.Add($vmtagname,$tagvalue)
Set-AzureRmResource -ResourceGroupName $tagRGname -ResourceName $azurevm -ResourceType Microsoft.Compute/virtualMachines -Tag $tags -Force `
}
}
Write-Host "All tagging is done"
I tried importing the right modules but this doesn't seem to affect the outcome.
Running the same commands in Cloud Shell does work correctly.
I can reproduce your issue, the error was caused by this part Get-AzureRmVM -Name $azurevm, when running this command, the -ResourceGroupName is needed.
You need to use the Az command Get-AzVM -Name $azurevm, it will work.
Running the same commands in Cloud Shell does work correctly.
In Cloud shell, azure essentially uses the new Az module to run your command, you can understand it runs the Enable-AzureRmAlias before the command, you could check that via debug mode.
Get-AzureRmVM -Name joyWindowsVM -debug
To solve your issue completely, I recommend you to use the new Az module, because the AzureRM module was deprecated and will not be updated.
Please follow the steps below.
1.Navigate to your automation account in the portal -> Modules, check if you have imported the modules Az.Accounts, Az.Compute, Az.Resources, if not, go to Browse Gallery -> search and import them.
2.After import successfully, change your script to the one like below, then it should work fine.
$azureConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
#Authenticate
try {
Clear-Variable -Name params -Force -ErrorAction Ignore
$params = #{
ServicePrincipal = $true
Tenant = $azureConnection.TenantID
ApplicationId = $azureConnection.ApplicationID
CertificateThumbprint = $azureConnection.CertificateThumbprint
}
$null = Connect-AzAccount #params
}
catch {
$errorMessage = $_
Throw "Unable to authenticate with error: $errorMessage"
}
# Discovery of all Azure VM's in the current subscription.
$azurevms = Get-AzVM | Select-Object -ExpandProperty Name
Write-Host "Discovering Azure VM's in the following subscription $SubscriptionID Please hold...."
Write-Host "The following VM's have been discovered in subscription $SubscriptionID"
$azurevms
foreach ($azurevm in $azurevms) {
Write-Host "Checking for tag $vmtagname on $azurevm"
$tagRGname = Get-AzVM -Name $azurevm | Select-Object -ExpandProperty ResourceGroupName
$tags = (Get-AzResource -ResourceGroupName $tagRGname -Name $azurevm).Tags
If ($tags.UpdateWindow){
Write-Host "$azurevm already has the tag $vmtagname."
}
else
{
Write-Host "Creating Tag $vmtagname and Value $tagvalue for $azurevm"
$tags.Add($vmtagname,$tagvalue)
Set-AzResource -ResourceGroupName $tagRGname -ResourceName $azurevm -ResourceType Microsoft.Compute/virtualMachines -Tag $tags -Force `
}
}
Write-Host "All tagging is done"

Start-AzVM : Your Azure credentials have not been set up or have expired Error

I made a Runbook in an automation account in Azure that will start and stop my VMs, but I keep getting credentials error while I am setting up the credentials in the runbook.
The error:
Start-AzVM : Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials. At Start-StopVM-Workflow:59 char:59 + + CategoryInfo : CloseError: (:) [Start-AzVM], ArgumentException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.StartAzureVMCommand
The runbook code:
{
Param
(
[String] $Action
)
################################################################
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzAccount `
-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
}
}
################################################################
if($Action -like "Stop")
{
$AzureVMs = Get-AzVM | ? {$_.resourcegroupname -notlike 'lab*'}
Write-Output $AzureVMs.count
#$AzureVMs = Get-AzVM | ? {$_.resourcegroupname -notlike 'lab*' -And $_.Tags["DontShut"] -notlike "Yes"}
#Write-Output "Stopping VMs"
foreach -parallel ($AzureVM in $Azurevms)
{
$temp = "Stop VM: " + $AzureVM.name
Write-Output $temp
$AzureVM | Stop-AzVM -Force
$count = $count+1
}
}
else
{
$AzureVMs = Get-AzVM | ?{$_.Tags["AutomaticStart"] -eq "Yes"}
Write-Output $AzureVMs.count
#Write-Output "Starting VMs";
foreach -parallel ($AzureVM in $AzureVMs)
{
$temp = "Start VM: " + $AzureVM.name
Write-Output $temp
$AzureVM | Start-AzVM
}
}
}
I tried using the Connect-AzRMAccount command but its no use.
If anyone knows a fix for this I'd be really thankful.
EDIT: After trying to update Az.Accounts and Az.Compute modules I still got the same error plus four new errors:
Install-module : NuGet provider is required to interact with NuGet-based repositories. Please ensure that '2.8.5.201' or newer version of NuGet provider is installed. At Start-StopVM-Workflow:13 char:13 + + CategoryInfo : InvalidOperation: (:) [Install-Module], InvalidOperationException + FullyQualifiedErrorId : CouldNotInstallNuGetProvider,Install-Module
Exception calling "ShouldContinue" with "2" argument(s): "A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or 'C:\Users\Client\AppData\Roaming\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install and import the NuGet provider now?" At Start-StopVM-Workflow:13 char:13 + + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : HostException
Install-module : NuGet provider is required to interact with NuGet-based repositories. Please ensure that '2.8.5.201' or newer version of NuGet provider is installed. At Start-StopVM-Workflow:12 char:12 + + CategoryInfo : InvalidOperation: (:) [Install-Module], InvalidOperationException + FullyQualifiedErrorId : CouldNotInstallNuGetProvider,Install-Module
Exception calling "ShouldContinue" with "2" argument(s): "A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or 'C:\Users\Client\AppData\Roaming\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install and import the NuGet provider now?" At Start-StopVM-Workflow:12 char:12 + + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : HostException
My current runbook script looks like this(Changes are in lines 12-14):
workflow Start-StopVM-Workflow
{
Param
(
[String] $Action
)
################################################################
$connectionName = "AzureRunAsConnection"
try
{
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-module -Force -name Az.Accounts
Install-module -Force -name Az.Compute
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzAccount `
-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
}
}
################################################################
if($Action -like "Stop")
{
$AzureVMs = Get-AzVM | ? {$_.resourcegroupname -notlike 'lab*'}
Write-Output $AzureVMs.count
#$AzureVMs = Get-AzVM | ? {$_.resourcegroupname -notlike 'lab*' -And $_.Tags["DontShut"] -notlike "Yes"}
#Write-Output "Stopping VMs"
foreach -parallel ($AzureVM in $Azurevms)
{
$temp = "Stop VM: " + $AzureVM.name
Write-Output $temp
$AzureVM | Stop-AzVM -Force
$count = $count+1
}
}
else
{
$AzureVMs = Get-AzVM | ?{$_.Tags["AutomaticStart"] -eq "Yes"}
Write-Output $AzureVMs.count
#Write-Output "Starting VMs";
foreach -parallel ($AzureVM in $AzureVMs)
{
$temp = "Start VM: " + $AzureVM.name
Write-Output $temp
$AzureVM | Start-AzVM
}
}
}
Your Runbook should ideally work with just the Az.Accounts and Az.Compute modules. I was able to test and execute your snippet with the Account I have.
I'd suggest you to cross-check your current Automation account/Runbook configuration, or create a new one as follows:
Create an Automation Account with Create Azure Run As account option enabled.
Import Az.Accounts and Az.Compute modules from the Powershell gallery via Azure portal.
Create a Powershell Runbook with your current code.
Test it.
If the issues recur despite doing this, please let me know and we can investigate further.
More about using Az modules with Azure Automation here.

Get-AzureBlobContent throwing error when run from Azure Automation account

I am receiving a failure while trying to download blob (JSON file) from Azure storage account from my Azure Automation account. It looks like an authorization issue.
This works on my local laptop, but does not work on Azure Automation Account. Does not work even if I make the container "public"
I have assigned OWNER privileges for the Automation accounts's service principle on the Resource Group (Automation account + Storage account stay in this RG) and specifically on the Storage Account as well:
Below is the code:
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"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
}
}
$config_file_resource_group_name = "vg-datalake-manjunath"
$config_file_storage_account_name = "datalakelog"
$primary_key = (Get-AzureRmStorageAccountKey -ResourceGroupName $config_file_resource_group_name -AccountName $config_file_storage_account_name).value[0]
$config_file_context = New-AzureStorageContext -StorageAccountName $config_file_storage_account_name -StorageAccountKey $primary_key
Get-AzureStorageBlobContent -Blob "mw_services.json" -Container "fwconfigfiles" -Destination "C:\temp\mw_services.json" -Context $config_file_context
get-content "C:\temp\mw_services.json" | write-output
ERROR:
Get-AzureStorageBlobContent : The remote server returned an error: (403) Forbidden. HTTP Status Code: 403 - HTTP Error
Message: This request is not authorized to perform this operation.
At line:30 char:2
+ Get-AzureStorageBlobContent -Blob "mw_services.json" -Container "fwc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureStorageBlobContent], StorageException
+ FullyQualifiedErrorId :
StorageException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.GetAzureStorageBlobContentCommand
The possible reason is that you may configure to selected networks to access.
If you enable this option, and whether you tick "allow trusted microsoft services to access", you would get this error, since automation is not listed under MS trusted services. see https://learn.microsoft.com/en-us/azure/storage/common/storage-network-security#trusted-microsoft-services.

Automation Runbook not able to set default subscription on run

Cloned a sample non classic runbook and attempted to set the subscription as default. This gives me following error:
Select-AzureSubscription : The subscription name {nameofsubscription} doesn't exist.
Parameter name: name
At step1_validate:18 char:18
+
+ CategoryInfo : CloseError: (:) [Select-AzureSubscription], ArgumentException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.SelectAzureSubscriptionCommand
How would it be possible to select or set a particular subscription as default? Below approaches throw above mentioned error:
Approach 1
Select-AzureSubscription -SubscriptionName $defaultSubscriptionname –Default
Get-AzureSubscription -SubscriptionId 123XXXXXXXXXXXXXXXXXX96eXX58 | Select-AzureSubscription
Approach 2
$subscriptionId = (Get-AzureRmSubscription | Out-GridView -Title 'Select Azure Subscription:' -PassThru).Id
Select-AzureRmSubscription -SubscriptionId $subscriptionId
Trying : To get particular resource name and make configurational changes, or to use Get-Azurewebsite cmdlet, setting a subscription appears mandatory.
Note: Hoping adding Service Principal used in the automation account to default subscription might help, I also tried to add the ApplicationId to Access control of Subscription as contributor. Though my Runbook being mentioned here and WebApps are in same subscription. Reference: https://blogs.technet.microsoft.com/knightly/2017/05/26/using-azure-automation-with-multiple-subscriptions/#comment-1555 ( Scenario for me is both are in same subscription )
EDIT: Pasting Code
<#
This PowerShell script was automatically converted to PowerShell Workflow so it can be run as a runbook.
Specific changes that have been made are marked with a comment starting with “Converter:”
#>
<#
.DESCRIPTION
To watch php version old in app, and if found turn it off and apply 5.6
.NOTES
AUTHOR: HBala
LASTEDIT: Jan 04, 2018
#>
workflow step1_validate {
# Converter: Wrapping initial script in an InlineScript activity, and passing any parameters for use within the InlineScript
# Converter: If you want this InlineScript to execute on another host rather than the Automation worker, simply add some combination of -PSComputerName, -PSCredential, -PSConnectionURI, or other workflow common parameters (http://technet.microsoft.com/en-us/library/jj129719.aspx) as parameters of the InlineScript
inlineScript {
$connectionName = "AzureRunAsConnection"
$myResourceGroupName = "DevstorageRG"
$defaultSubscriptionname = "StandardDevStaging"
$newPhpVersion = "5.6"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"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
}
}
#Get all ARM resources from all resource groups
$ResourceGroups = Get-AzureRmResourceGroup
foreach ($ResourceGroup in $ResourceGroups)
{
Write-Output ("Showing resources in resource group " + $ResourceGroup.ResourceGroupName)
if( $ResourceGroup.ResourceGroupName -eq $myResourceGroupName ){
$Resources = Find-AzureRmResource -ResourceGroupNameContains $ResourceGroup.ResourceGroupName | Select ResourceName, ResourceType
ForEach ($Resource in $Resources)
{
Write-Output ($Resource.ResourceName + " of type " + $Resource.ResourceType)
Write-Output ($Resource.ResourceName + " of type " + $Resource.ResourceType)
#Switch-AzureMode AzureServiceManagement
# Local powershell connects and works perfect with what I wanted to achieve.
# On Automation account, Runbook migration, it threw Azure subcription not set error for Set-AzureWebsite.
# so remove rest of the code and focused on few options to get the default as below
# which led me to post the thread.
#
# Approach 1
Select-AzureSubscription -SubscriptionName $defaultSubscriptionname –Default
Get-AzureSubscription -SubscriptionId 1238XXXXXXXXXXXe5XXXX8 | Select-AzureSubscription
# Approach 2
$subscriptionId = (Get-AzureRmSubscription | Out-GridView -Title 'Select Azure Subscription:' -PassThru).Id
Select-AzureRmSubscription -SubscriptionId $subscriptionId
Write-Output ( "==============Subscription ID :===========")
Write-Output( $subscriptionId)
# Wants to update config / php version parameters.
Set-AzureWebsite -Name $Resource.ResourceName -HttpLoggingEnabled 1 -PhpVersion 5.6
# Had tried this as well which was suggested by Jason. But appears not working..
# looks like I have messed it up.
Get-AzureRmWebApp -ResourceGroupName $myResourceGroupName -Name $Resource.ResourceName
Set-AzureRmWebApp -ResourceGroupName $myResourceGroupName -Name $Resource.ResourceName -HttpLoggingEnabled 1 -PhpVersion 5.6
}
}
Write-Output ("Completed!#Line83")
}
}
}
Hoping adding the serviceprincipal type addition for the
automationaccount to default subscription might help
You are right, we can use Azure automation account connections to select subscription.
For example, we can new a connection and the type is Azure service principal.
like this:
Then use this powershell script to select the connection:
$connectionName = "jason"
try
{
# Get the connection "jason "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"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
}
}
In this way, we can use connection to select subscription.
By the way, we can follow this article to create service principal.

Resources