Connect-AzAccount Powershell on-prem - azure

I am new to Azure and I've successfully installed PowerShell on my macOS. Now I want to run get-azvm command and stop/delete a vm from on-prem (not cloud shell).
First thing I did from Terminal:
1. PWSH to launch PowerShell
2. Connect-AzAccount, browser opens to authenticate and I get an error:
Connect-AzAccount xx: Device authentication is required.
Trace ID: xx
Correlation ID: xx
+ CategoryInfo : CloseError: (:) [Connect-AzAccount], AadAuthenticationFailedException
I continue with az login command. Result:
You have logged in. Now let us find all the subscriptions to which you have access...
{
}
I run: get-azvm and get another error:
get-azvm : No subscription found in the context. Please ensure that the credentials you provided are authorized to access an Azure subscription, then run Connect-AzAccount to login.
At line:1 char:1
Please, what am I doing wrong? Do I need to register my on-prem machine somewhere?
Thanks for the help.

As mentioned in above comment - you might have conditional access policies enabled on your Azure AD so you might want to check it out and confirm.
Secondly, if that's not the case - try running commands below before you access your azure resources
Add-AzAccount
Get-AzSubscription -SubscriptionId "your_azure_subscription_id" | Select-AzSubscription
$vm = Get-AzVM -ResourceGroupName "your_vm_resource_group_name" -Name "your_vm_name"
Hope it helps?

According to the error from Connect-AzAccount, Looks your account is MFA-enabled, please use the authentication methods to authenticate. Or you can create a service principal, assign a role for it in the subscription, then you can login with the service principal and use it to Get-AzVM, details here.
I continue with az login command. Result: You have logged in. Now let us find all the subscriptions to which you have access..
You should note, Connect-AzAccount is used to login the Azure Powershell, az login is used to login the Azure CLI, they are different. From the output, looks you logged in successfully in Azure CLI, you could use az account set --subscription <subscription-id> to set the subscription which you want to get the VMs from, then use az vm list to list VMs.

Related

Azure PowerShell: Get-AzVM does not display the output

According to this Official document example from MS Azure team, the following command should display all the VMs in my current subscription. But when I logged-in with my subscription and run the following command, it just brings me back to the command line with no output and no error. I do have VMs in this subscription, and the same login with the same subscription is working for other tasks I am performing in the same session. Question: What I may be missing here, and how can we resolve the issue?
PS C:\Users\MyUserName> Get-azVM
PS C:\Users\MyUserName>
Are you Signed into Azure Connect-AzAccount
Do you have more than one subscription?
If so you might need to switch subscriptions.
Set-AzContext -SubscriptionId "xxxx-xxxx-xxxx-xxxx"

Connecting Azure with PS: Please try logging in with different credentials or a different subscription ID

1) I open Azure portal with my user account john.smith#mycompany.com at subs id "111111111111111111111111111". I can successfully create new resource as I'm contributor.
2) I run Az command to create resource and connect with following.
Connect-AzAccount -Subscription "111111111111111111111111111"
ERROR:
Connect-AzAccount : The provided account john.smith#mycompany.com does not have access to
subscription ID "111111111111111111111111111". Please try logging in with different
credentials or a different subscription ID.
What could be wrong?
Try the following link it might help you if you haven't figured it out already
Connect-AzAccount - how to avoid azure device authentification?

Azure KeyVault: SPN KeyVault Access Denied

I am using below Azure Powershell command in VSTS.
(Get-AzureKeyVaultSecret -vaultName "debugkv" -name "CoreConfig-StorageAccount-AccessKey")
I am getting ##[error]Access denied error while running it in VSTS but loclaly it works fine.
I have added the SPN in KV's access policies also with GET and SET permissions for secrets.
Need help in troubleshooting it.
To link VSTS to you need to give the Service Principal, which forms the Service Endpoint in VSTS, access to the Key Vault; you already know this.
What can be confusing is that you can assign the application and the service principal to have access to the key vault depending on your use case. Therefore, you must ensure that you assign the right object to the access policy.
The best way to ensure you assign the right object is to do it through Azure Powershell.
Running a signed in Azure Powershell session:
$spObjectId = Get-AzureRmAdServicePrincipal -SearchString <ServicePrincipalName> | Foreach-Object {$_.Id}
Set-AzureRmKeyVaultAccessPolicy -VaultName <VaultName> -ObjectId $spObjectId -PermissionsToSecrets Get,Set
If you wanted to see further details (objectids, permissions etc) of the access policies you can get these through Powershell also:
Get-AzureRmKeyVault -VaultName <VaultName> | Foreach-Object {$_.AccessPolicies}

Azure Powershell - automating Login-AzureRmAccount AD Login - for Azure function

I have this Azure Powershell script, which successfully backs up a SQL Azure DB to Azure Blob.
In its current form, it requires me to log in via AD.
I now need to implement this script to execute via a Azure Function at specific intervals.
The first snippet of the script:
$subscriptionId = "YOUR AZURE SUBSCRIPTION ID"
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId $subscriptionId
I thus need to not use Login-AzureRmAccount, but replace it with a method that does not require human input.
I have found this link:
https://cmatskas.com/automate-login-for-azure-powershell-scripts/
In short, the author:
Creates an Azure AD Application (with its own password)
Creates a Service Principal
Assigns Permissions to the Service Principal
This is a once-off manual creation - which is perfect.
The author then logs in to this newly created application
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId e801a3ad-3690-4aa0-a142-1d77cb360b07 -ServicePrincipal
My questions:
Is this what I should do to be able to automate my application and prevent human login?
This Azure AD app created in step 1 - can I use this app as a starting point in my of my Azure functions?
Yes, you can use that route, or use certificate auth, or use an Azure AD user, it can login with user\password, but is considered less secure than service principal.
Yes, you can use one service principal for any number of Azure Functions you would like to.
To use Azure PowerShell in Azure Functions, you may refer to the following response in another SO thread. The example is an HTTP-Trigger, but you can modify it to use a Timer-Trigger for your use-case. Here's the link:
Azure Function role like permissions to Stop Azure Virtual Machines
Run PowerShell as Administrator, you need to install AzureRM in PowerShell,
Login to Azure
Login-AzureRmAccount
Enter your Azure credentials
To get your subscription(s) details
enter
Get-AzureRmSubscription
Use the subscription id to select the subscription.
Select-AzureRmSubscription -SubscriptionId xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Save the AzureProfile using the below command
Save-AzureRmProfile -Path "C:\AzureScripts\profile.json"
The json file can be used to login to Azure
Select-AzureRmProfile -Path "C:\AzureScripts\profile.json"
Put this line on top of you .ps1 file, you does not require human input.
Ref : http://www.smartcoding.in/blog/auto-login-azure-power-shell

Azure Credentials error in Azure Automation

I'm trying to create an Azure Automation job to create a standard set of tags/values in a subscription.
Working with Tags requires AzureResourceManager, which is not available in Automation out of the box (Go vote for this feedback item!), so I followed these steps to upload the ARM module.
When I test my runbook I get the following output:
-------------------------
PSComputerName : localhost
PSSourceJobInstanceId : a8b85213-ee0f-40ea-842f-d33f2e87c910
Id : xxxxx-56ad-42c2-97f4-e364456fc4a6
Name : xxxxx
Environment : AzureCloud
Account : my-service-principal-app-id
Properties : {Default, Tenants, SupportedModes}
-------------------------
New-AzureTag : Your Azure credentials have not been set up or have expired, please run Add-AzureAccount to set up your
Azure credentials.
At Add-SubscriptionTags:41 char:41
+
+ CategoryInfo : CloseError: (:) [New-AzureTag], ArgumentException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Tags.Tag.NewAzureTagCommand
Here's my runbook:
workflow Add-SubscriptionTags
{
param
(
# Subscription
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$SubscriptionName
)
# Get the PowerShell credential and prints its properties
$cred = Get-AutomationPSCredential -Name 'AzureMaint'
# Connect to Azure
Add-AzureAccount -Credential $cred -ServicePrincipal -Tenant 'xxx-49ab-8a9c-4abce32afc1e' | Write-Verbose
# Set subscription
$subscription = Select-AzureSubscription -SubscriptionName $SubscriptionName -PassThru
write-output '-------------------------'
write-output $subscription
write-output '-------------------------'
# Add tags (Requires AzureResourceManager module)
New-AzureTag -Name 'Managed' -Value $true
New-AzureTag -Name 'Managed' -Value $false
}
The AzureMaint PSCredential contains a service principal ID and key, and the service principal has been granted the Contributor role on the specified subscription. I can do Add-AzureAccount in the ISE with those credentials and add tags just fine. Since it successfully prints the subscription info I assume that means Add-AzureAccount was successful, so why do I get the error?
Update:
I created a new Automation Account without the ARM module and I'm still having the same issue, although the error message is slightly different:
Your Azure credentials have not been set up or have expired, please run Add-AzureAccount
to set up your Azure credentials. (Your Azure credentials have not been set up or
have expired, please run Add-AzureAccount to set up your Azure credentials. (Unable
to retrieve service key for ServicePrincipal account xxx-4a00-becf-952fda93edc5.
Please run the Add-AzureAccount cmdlet to supply the credentials for this service principal.))
So now I'm wondering if it doesn't like me using a Service Principal?
Just to update here, we've discovered that service principal authentication does not work in Azure Automation currently. Given you are trying to use a service principal, that is the reason for the issues you are hitting.
For now, a user principal should be used to work around this issue.
Please see the following for more info:
Authenticating to Azure Resource Manager with a Service Principal in Azure Automation
https://github.com/Azure/azure-powershell/issues/655
Using ARM cmdlets in Azure Automation is not officially supported yet. That said, various people have been successful doing so. Are your ARM and Azure PowerShell modules the same version? Weird things can happen if they are loaded side by side but are not the same version.

Resources