Why does Azure Powershell script think I'm not logged-in? - powershell

I'm building an Azure Powershell script to add a DB firewall rule.
I first of all login using Add-AzureRmAccount:
$userName = "j---#s---.--"
$securePassword = ConvertTo-SecureString -String "---------" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $securePassword)
Add-AzureRmAccount -Credential $cred
This returns the following, which I assume means that I have successfully logged-in:
Environment : AzureCloud
Account : j---#s---.--
TenantId : [GUID]
SubscriptionId : [GUID]
SubscriptionName : Visual Studio Ultimate mit MSDN
CurrentStorageAccount :
At this stage I can query for my subscription:
Get-AzureRmSubscription –SubscriptionName "Visual Studio Ultimate mit MSDN" | Select-AzureRmSubscription
Which returns
Account : j---#s---.--
Environment : AzureCloud
Subscription : [GUID]
Tenant : [GUID]
So far, so good.
However, whenever the script calls anything at the resource-group level, such as
Find-AzureRmResource -ResourceNameContains "-----NorthEurope"
then it responds with
Run Login-AzureRmAccount to login.
The exception detail is
+ CategoryInfo : InvalidOperation: (:) [Find-AzureRmResource], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.FindAzureResourceCmdlet
Which doesn't help me at all.
I've even explicitly called
Login-AzureRmAccount $cred
prior to the Find-AzureRmResource call, but this makes no difference.
Of course, what I'm ultimately looking to do is call
New-AzureRmSqlServerFirewallRule -ResourceGroupName "-----NorthEurope" `
-ServerName "-----.database.windows.net" `
-FirewallRuleName "test1" `
-StartIpAddress "-.-.-.-" `
-EndIpAddress "-.-.-.-"
But that encounters the same exception.
Can anyone explain why I keep getting asked to run Login-AzureRmAccount after I've apparently successfully added the account?
Solution
What got it working for me, as #Tomer alluded to in the comments, was to forcefully re-get all AzureRm modules.

Related

Powershell "Connect-PowerBIServiceAccount" error

I'm experiencing an issue concerning this command (Connect-PowerBIServiceAccount), I everytime get the same error :
Connect-PowerBIServiceAccount : Failed to populate environments in settings
Au caractère Ligne:1 : 1
Connect-PowerBIServiceAccount
CategoryInfo : WriteError: (Microsoft.Power...IServiceAccount:ConnectPowerBIServiceAccount)
[Connect-PowerBIServiceAccount], Exception
FullyQualifiedErrorId : Failed to populate environments in settings,Microsoft.PowerBI.Commands.Profile.ConnectPowerBIServiceAccount
I've tried various things already like :
$password = "mypassword" | ConvertTo-SecureString -asPlainText -Force
$user = "surname.name#company.com"
$credential = New-Object System.Management.Automation.PSCredential($user, $password)
Connect-PowerBIServiceAccount -Credential $credential
or
Connect-PowerBIServiceAccount -Environment Public
or
Connect-PowerBIServiceAccount -TenantId "company.com" -ServicePrincipal -Credential (Get-Credential)
I get the same result as well with Login-PowerBI or Login-PowerBIServiceAccount.
And I can't use -CertificateThumbPrint, I don't have access to the Power BI liscence key of my company.
All the PowerBI modules for PowerShell are installed (and I tried as well reinstalling them), my current version of Powershell is 5.1.19041.1645 and my .NET Framework version is 4.8
If you have any clue they are welcome.

Add-AzureRmAccount : Sequence contains no element (Not working for Gmail accounts too)

I have created a 'Free Trial' account with my personal email ID which is a Gmail ID. I'm getting the error :
Add-AzureRmAccount : Sequence contains no elements At line:1 char:1
+ Add-AzureRmAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand
The code I'm running is
$username = "abc#gmail.com"
$password = "something"
$secpass = $password | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secpass
Add-AzureRmAccount -Credential $cred
Are there certain type of accounts/subscriptions for which logging in like this is supposed to work?
Windows Live ID credentials cannot be used for a non-interactive login. This error message is described as part of this issue which has been raised because it needs improving.
I think you either need to use Login-AzureRmAccount to login interactively or create a Service Principal for login, per this guide: https://learn.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azurermps-4.2.0
Log in with a service principal
Service principals provide a way for you to create non-interactive
accounts that you can use to manipulate resources. Service principals
are like user accounts to which you can apply rules using Azure Active
Directory. By granting the minimum permissions needed to a service
principal, you can ensure your automation scripts are even more
secure.
If you don't already have a service principal, create one.
Log in with the service principal:
Login-AzureRmAccount -ServicePrincipal -ApplicationId "http://my-app" -Credential $pscredential -TenantId $tenantid

List all my Azure websites using an Azure Powershell Function

Im testing the new Azure Functions, and would like to write a function that return all my Azure Websites. But needless to say I run into some problems, and documantation is still minimal.
run.ps1
# Get the input request
$in = Get-Content $req -Raw | ConvertFrom-Json
Write-Output "Loading..."
Get-AzureRmSubscription -SubscriptionId $in.SubscriptionId | Select-AzureRmSubscription
$Result = Get-AzureWebsite
Write $Result
This function take the subscription id as a parameter, and is supposed to list the available websites. But I get this exception.
2017-06-13T12:43:57.763 Get-AzureRmSubscription : Run Login-AzureRmAccount to login.
So I tried to add Login-AzureRmAccount but then I get.
2017-06-13T12:45:04.959 Login-AzureRmAccount : Error HRESULT E_FAIL has been returned from a call to a COM component.
And that is where I stand now.
Update
After help from #4c74356b41 I now am able to login. My code for logging in looks like this.
$subscriptionId = "<SubscriptionId>"
$tenantid = "<TenantId>"
$clientid = "<ApplicationId>"
$password = "<Password>"
$userPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $clientid, $userPassword
Add-AzureRmAccount -TenantId $tenantid -ServicePrincipal -SubscriptionId $subscriptionId -Credential $userCredential
I can see that this work when I test the code. But as soon as I add this line.
Select-AzureSubscription -Current -SubscriptionId $subscriptionId
I get this exception.
Select-AzureSubscription : The subscription id <SubscriptionId> doesn't exist.
Parameternavn: id
At line:11 char:1
+ Select-AzureSubscription -Current -SubscriptionId $subscriptionId
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Select-AzureSubscription], ArgumentException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.SelectAzureSubscriptionCommand
I also tried to add this line.
Get-AzureRmSubscription –SubscriptionId $subscriptionId | Select-AzureRmSubscription
Which look like is working, it only thows a warning WARNING: Unable to acquire token for tenant 'Common' but still list the correct subscription details without any exceptions.
Then when I try
Get-AzureWebsite
I get this exception.
Get-AzureWebsite : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.
At line:15 char:1
+ Get-AzureWebsite
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureWebsite], ApplicationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Websites.GetAzureWebsiteCommand
Well, how do you expect to work with your subscription without authenticating? would you like anybody to be able to modify your resources without any validation at all? so you need to authenticate before doing anything.
Working with powershell in Azure Function is no different from working with powershell on your machine (except module management).
To login you could use service principal auth ang login with something like:
Add-AzureRmAccount -TenantId $tenantid -ServicePrincipal -SubscriptionName $name `
-Credential ([pscredential]::new($clientid,(ConvertTo-SecureString -String $password -AsPlainText -Force)))
you can replace variables (hardcoded in the code) with environment variables.
Add 4c74356b41's answer, Get-AzureWebsite is an Azure Classic mode cmdlet. Now, you login your ARM subscription, so, it requires you login classic subscription. Select-AzureSubscription is a classic cmdlet that use to select classic subscription.
In Azure ARM mode, website is renamed Webapp, you could check Azure App Service announcement.
So, if you want to list your all webapp, you should use cmdlet Get-AzureRmWebApp.
More information please refer to this link: Using Azure Resource Manager-Based PowerShell to Manage Azure Web Apps.

office 365 powershell login with service principal or OAuth2

I can find information about how to create Service Principals for Office365 with Powershell - but I can't find any how to login with them in Powershell. Is this not possible? I am currently using this code, that works with my Admin account but not with service credentials (that work with Azure) :
$AdminName = "application-id"
$Pass = ConvertTo-SecureString "application-key" -AsPlainText –Force
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
# Azure Login working
#$tenantId = "tenant-id"
#Add-AzureRmAccount -Credential $Cred -ServicePrincipal -TenantId $tenantId
# MSOnline / Office365-Login not working
Import-Module MSOnline
Connect-MsolService -Credential $Cred
The error I get at the "Connect-MsolService" is :
Connect-MsolService : Unable to authenticate your credentials. Make
sure that your user name is in the format: <username>#<domain>. If
this issue persists, contact Support.
Connect-MsolService -Credential $Cred
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException
FullyQualifiedErrorId : 0x80048862,Microsoft.Online.Administration.Automation.ConnectMsolService

Running Set-AzureRmAppServicePlan from Automation script (RunBook)

I'm trying to run Set-AzureRmAppServicePlan from automation runbook but getting
Set-AzureRmAppServicePlan : Run Login-AzureRmAccount to login. At
line:20 char:1
+ Set-AzureRmAppServicePlan -ResourceGroupName "...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Set-AzureRMAppServicePlan], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.WebApps.Cmdlets.AppServicePlans.SetAzureAppServicePlanCmdlet
Note that actual runbook authentication using Automation Credential is successful.
And I can run this script from local powershell using
Login-AzureRmAccount
Add-AzureRmAccount
Set-AzureRmAppServicePlan...
Is it possible at all to run this from automation without interactive login?
Thanks
Pavel
figure it out.. pretty simple instead of
Add-AzureAccount - which is used in sample runbook Get-AzureVMTutorial created automatically
need to use
Add-AzureRmAccount
for use with Azure Resource Manager cmdlet requests like
Set-AzureRmAppServicePlan
Leaving question / answer here.. might still help someone
If you are not using MFA, pls see the following cmds, replace 'yourPassword', 'yourUserName', 'yourEnvironment', 'yourSubscriptionId', 'yourTenantId' with your own message and put it to your script then you can login without interactive page.
$userPassword = ConvertTo-SecureString -String "yourPassword" -AsPlainText -Force
$psCred = new-object -typename System.Management.Automation.PSCredential -argumentlist 'yourUserName', $userPassword
$credential = Get-Credential -Credential $psCred
add-azureRmAccount -EnvironmentName 'yourEnvironment' -credential $credential -subscriptionId 'yourSubscriptionId' -tenant 'yourTenantId'