Select Subscription in azure automation - azure

I'm trying to get an automation script up and running in Windows Azure.
I got an error telling the I have to use Select-AzureSubscription.
This one is failing with the following error:
Error: Select-AzureSubscription : The subscription named 'xxx' cannot be found. Use Set-AzureSubscription to
initialize the subscription data.
Parameter name: name
At my-script:15 char:15
+
+ CategoryInfo : CloseError: (:) [Select-AzureSubscription], ArgumentException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.SelectAzureSubscriptionCommand
So I used Set-AzureSubscription but this one is failing as well.
I tried passing the subscription name and the subscription ID.
Did someone managed to properly configure this?

You need to set up authentication to Azure using Add-AzureAccount. See https://msdn.microsoft.com/en-us/library/azure/dn865019.aspx for more details.

Before Selecting subscription you need to add your azure account through any of the methods available. The simplest one is using credentials
$username = "your username"
$password = ConvertTo-SecureString 'yourpassword' –asplaintext –force
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
<#you can also use Azure assets to store the credential and use it directly like
$Cred=Get-AutomationPSCredential -Name $AzureAccountCredentialName
#>
Add-AzureAccount -Credential $Cred
#Now select your subscription

Related

How do I get groups from AAD using Powershell Function App?

I want to get all users from certain groups in AAD using Powershell with a Function app, but I keep getting permission errors and I don't know how to assign them.
$groupsAD = [System.Collections.ArrayList]#()
$groupsAD.Add('Group1')
$groupsAD.Add('Group2')
foreach ($groupAD in $groupsAD) {
$group = Get-AzADGroup -DisplayName $groupAD
# further code
}
The error:
[Error] ERROR: Insufficient privileges to complete the
operation.Exception :Type : System.ExceptionMessage :
Insufficient privileges to complete the operation.HResult :
-2146233088CategoryInfo : InvalidOperation: (:) [Get-AzADGroup], ExceptionFullyQualifiedErrorId :
Microsoft.Azure.Commands.ActiveDirectory.GetAzureADGroupCommandInvocationInfo
:MyCommand : Get-AzADGroupScriptLineNumber : 16OffsetInLine
: 14HistoryId : 1ScriptName :
C:\home\site\wwwroot\HttpTrigger1\run.ps1Line : $group =
Get-AzADGroup -DisplayName $groupADPositionMessage : At
C:\home\site\wwwroot\HttpTrigger\run.ps1:16 char:14+ $group =
Get-AzADGroup -DisplayName $groupAD
When creating this function locally it works fine after I authenticate with Connect-AzAccount.
Also tried to create an identity and authenticate it with it, but as far as I know it's for Azure resources not AAD.
For this problem, here provide two solutions for your reference:
1. If you use username/password to do authentication in Connect-AzAccount command, you need to make sure the user account has required permission for get AD group. Then use the code below in your function:
$User = "{username}"
$PWord = ConvertTo-SecureString -String "{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
Connect-AzAccount -Credential $Credential
$group = Get-AzADGroup -DisplayName "{group name}"
2. If you do not want to use username/password to do authentication in your function. You can use service principal to do it.
First you need to register an app in your Azure AD, I registered an app named "huryGetToken6" in my Azure AD.
Then click "Certificates & secrets" tab, new client secret. Copy the client secret to your notepad.
Then add the permission to the registered app, do it with the steps in below screenshots.
Please do not forget click "Grant admin consent for xxx" after add the permissions to registered app.
After that, you can use the code below in your function to get AD group:
$username = "{client id/application id}"
$password = "{client secret}"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd
Connect-AzAccount -Credential $Credential -Tenant "{tenant id}" -ServicePrincipal
$group = Get-AzADGroup -DisplayName "huryGroup"
For the params in above commands, you can find the client id/application id and tenant id on the "Overview" page of your registered app.

Azure Automation - Login with AD User throws error

I am trying to login to Azure from Azure Automation using my AD credential. However seems like I am doing something wrong and it's throwing error while testing.
$Cred = Get-AutomationPSCredential -Name 'DefaultAzureCredential'
$null = Add-AzureRmAccount -Credential $Cred -ErrorAction Stop -ErrorVariable err
if($err) {
throw $err
}
Get-AzureRmResourceGroup -Name "my-resource-group"
Error:
Get-AzureRmResourceGroup : No subscription found in the context. Please ensure that the credentials you provided are
authorized to access an Azure subscription, then run Login-AzureRMAccount to login.
At line:8 char:1
+ Get-AzureRmResourceGroup -Name "my-resource-group"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureRmResourceGroup], ApplicationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.GetAzureResourceGroupCommand
Update:
When I run Get-AzureRm-Context from Azure Automation script it shows me following which is completely different than when I run the same command from Azure Cloud Shell. Should I do things differently ?
Account Environment Subscription Tenant
------- ----------- ------------ ------
AzureCloud
Looking at the error, i do not see an issue with Login or credential. The error is in the get-AzureRmResourceGroup No subscription found in the context.
This happens when credential provided does not have a subscription. If you are sure account has subscription, then the issue might be with the module loaded in Azure Automation.

Get-AzResourceGroup : 'this.Client.SubscriptionId' cannot be null

Having a bit of an issue with Azure and Powershell. I'm just checking to see if a resource group exists and I keep hitting this error. The next step after this is to create the resource group if it does not exist, but that is also throwing the same error. Was hoping someone might be able to suggest some workarounds or fixes.
Please note, I have access to the subscriptions, I can see them and sucessfully set the default subscription as can be seen in the script below.
Full Error Returned
'this.Client.SubscriptionId' cannot be null.
At **********************\envir\create-env.ps1:21 char:1
+ Get-AzResourceGroup -Name $resourceGroup -ErrorVariable $doesNotExist ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzResourceGroup], ValidationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceGroupCmdlet
I've just installed the Az module, version details below.
Version Name Repository
------- ---- ----------
1.6.0 Az PSGallery
I'm just running a pretty straight forward script (below), I thought it might be something to do with a default subscription not been set, but setting that has made no difference.
$passwd = ConvertTo-SecureString $servicePrincipalKey -AsPlainText -Force
$pscredential = New-Object
System.Management.Automation.PSCredential($servicePrincipalUserName, $passwd)
Connect-AzAccount -ServicePrincipal -Credential $pscredential -TenantId $tenantId
Select-AzureSubscription -Default -SubscriptionName $subscriptioName
Get-AzResourceGroup -Name $resourceGroup -ErrorVariable $doesNotExist
I then get the error listed above.
I found the problem, the Service Principal I had created did not have sufficient access to the subscription as suggested by #4c74356b41, I ended up giving it a role of Contributor and that resolved the problem.

login to azure account without popup using powershell

I'm trying to create Azure VM using powershell.I have also the script to create it.
First I need to login into Azure account :
Login-AzureRMAccount
This gives a pop-up to enter the credentials.
Second I need to run the below script:
$UserName = "username"
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-AzureRmVm `
-ResourceGroupName "RG1" `
-Name "VM1" `
-ImageName "Image1" `
-Location "West US" `
-Credential $psCred
This is creating the VM successfully.
But now , I need to make these scripts run automatically, when ever there is requirement. The problem I'm facing is, the login step gives a popup to enter the credentials which I do not want. So I have tried something like this, but didn't work.
$username = "loginname#organization.com"
$SecurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
Login-AzureRmAccount -Credential $cred
The error message it is giving is :
Login-AzureRmAccount : accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed: The underlying connection was closed: An unexpected error occurred on a send.
At line:4 char:1
+ Login-AzureRmAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
Can anyone tell me what this means and how to rectify this? Thanks!
If you are planning to automate any services into Azure using PowerShell, then I'd recommend connecting azure using Service Principal rather than your own credentials, it will be a secure way to connect.
What is Service principal?
An Azure service principal is a security identity used by user-created
apps, services, and automation tools to access specific Azure
resources. Think of it as a 'user identity' (username and password or
certificate) with a specific role, and tightly controlled permissions.
It only needs to be able to do specific things, unlike a general user
identity. It improves security if you only grant it the minimum
permissions level needed to perform its management tasks.
Follow this tutorial to create a service principal
I also have published a sample PowerShell workflow into Microsoft gallery for creating Service Principal you can also follow that.
Once you created your service principal, you can use the below PowerShell commands to login into azure without any popup's
$applicationId = "<service prinicple application id>";
$securePassword = "<service prinicple password>" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -TenantId "<your tenantid>"
Update1:
For some reason/bug the above will get fails. Refer this github issue
To solve this
Add the two lines before the script
Import-Module -Name AzureRM.Profile
Remove-AzureRmAccount
Update 2:
AzureRM will no longer receive new cmdlets or features. However, the AzureRM module is still officially maintained and will get bug fixes through December 2020.
You have to use the new Azure PowerShell Az module
Basically you can achieve this for all of your PowerShell sessions by adding the Logging in part as part of the $PSProfile. I use this trick to skip the login popup, so whenever i open powershell my account is automatically logged in.
Open Windows PowerShell as an administrator
Type Notepad $profile
A notepad file will be opened and here you can paste the below code to
log in automatically whenever it is opened.
$username = “”
$password = “”
$securepasswd = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($username, $ securepasswd)
Connect-AzureRmAccount -Credential $cred

Azure Automation: VM shutdown runbook not working on new VM

I recently had to delete and re-install my VM due to an issue with the VM locking up. Now that the VM is back online, I noticed the shutdown automation is not working. It was working fine before I ran into the issue with the VM. Below is the PS script from the runbook, it returns the following error:
Correlation ID: 72fa8e58-89f1-4612-bc43-1b05876c2bff
Timestamp: 2015-08-25 06:04:14Z: The remote server returned an error: (401) Unauthorized.
At Shutdown:6 char:6
+
+ CategoryInfo : CloseError: (:) [Add-AzureAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.AddAzureAccount
8/24/2015 11:04:25 PM, Error: Get-azurevm : No default subscription has been designated.
Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.
At Shutdown:8 char:8
+
+ CategoryInfo : CloseError: (:) [Get-AzureVM], ApplicationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.GetAzureVMCommand
Any idea what I am missing to get this working with new VM? I have been wracking my brain for something with the credentials that would not include this new VM, but have come up empty handed.
workflow Shutdown
{
$Cred = Get-AutomationPSCredential -Name "auto"
Add-AzureAccount -Credential $Cred
$vms = Get-azurevm
foreach($VM in $VMS)
{
$VMName = $VM.Name
Stop-AzureVM -ServiceName $VM.ServiceName -Name $VM.Name -Force
Write-Output "Shutting down VM : $VMName "
}
}
I think you should also add the subscription name (select-azuresubscription in the error log) in the script you are using. There are quite some examples of doing this in various ways in the TechNet Script libraries like this one https://gallery.technet.microsoft.com/scriptcenter/Stop-Azure-VM-with-OrgID-41a79d91
I created a new user, granted them admin rights to the subscription, and updated the credential. That seemed to fix it, guessing it was something with the existing co-admin account not having access to the new VM.

Resources