I am trying to login to Azure from VS Code so that i can run Terraform scripts.
So i created a SP by following the below commands.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal `enter code here`
After running the Add-AzAccount it displays me the Account Name, Subscription Name, Tenant ID and Environment.
But when i now try to run terraform plan from my VS Code so that i can check what all things will be deployed in my azure environment, it throws me this error below :
Error: Error building account: Error getting authenticated object ID: Error parsing json result from
the Azure CLI: Error waiting for the Azure CLI: exit status 1: AADSTS50076: Due to a configuration
change made by your administrator, or because you moved to a new location, you must use multi-factor
authentication to access '00000002-0000-0000-c000-000000000000'.
Trace ID: 19a89f14-0138-4fbd-8d67-5f30c95e5701
Correlation ID: 7d80e2b1-49cc-4f42-9010-401e4453d13e
Timestamp: 2021-02-05 16:39:03Z
I have also tried logging in by typing Login-AzAccount and logged in using Multi Factor Auth, but still i see the above error.
Any reason why i am still getting the error while trying to run Terraform Plan even though i am logged in to Azure from my VS Code
As discussed in the comment:
You need to use Azure CLI and run az login first. Az-Powershell is not being used by Terraform under the hood.
Related
I have been battling with an issue for day now, Anytime i try to deploy from azure pipeline, i get this error:
Failed to create an app in Azure Active Directory. Error: The directory object quota limit for the Principal has been exceeded. Please ask your administrator to increase the quota limit or delete objects to reduce the used quota.
came across a resource on stackoverflow from:
Can't create new Service Principals in Azure despite being under quota
and followed the guide in the resource, but still didnt work.
Get-AzureADDeletedApplication -all 1 | ForEach-Object { Remove-AzureADdeletedApplication -ObjectId $_.ObjectId }
this is the error i get running the above command :
Get-AzureADDeletedApplication: The term 'Get-AzureADDeletedApplication' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Please note the command was run in powershell knowing it is a powershell command. Also, if there is a cli command to use to clear this, that would be really appreciated.
I would be gad if anyone can help cause this is frustrating and i am behind time.
Thanks guys
I tried in my environment and got similar error when I run the same commands:
Get-AzureADDeletedApplication
This error occurs due to that you have not install azureAD or install azureADPreview
Install the module
install-module AzureAD or install-module AzureADPreview
Connect with your azure active directory by following commands with your credentials.
Connect-AzureAD
When I connected with azure ad i can list all the DeletedazureADApplication.
First I tried to delete the particular AD application it is successfully deleted.
Remove-AzureADdeletedApplication -ObjectId 00000000-0000-0000-0000-000000000000
Later I tried to delete all the application with following commands and got successfully deleted the azureADdeletedapplication.
Get-AzureADDeletedApplication -all 1 | ForEach-Object { Remove-AzureADdeletedApplication -ObjectId $_.ObjectId }
Reference:
https://learn.microsoft.com/en-us/powershell/module/azuread/get-azureaddeletedapplication?view=azureadps-2.0
I am trying to create a Runbook which does some maintenance in Active Directory. On creation of an Automation Account an "RunAs" account was created. In the runbook I connect to AD using the below command.
$connectionName = "AzureRunAsConnection"
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to AzureAD..."
Connect-AzureAD `
-TenantId $servicePrincipalConnection.TenantId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-LogLevel Info
This command runs fine, however the subsequent use of AD CMDLETS gives the following error,
$Users = Get-AzureADUser
Get-AzureADUser : Error occurred while executing GetUsers Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation.
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
The same is true for other CMDLETS in the AD module, not just this I have tried adding API permission through the registered application (relating to the Automation Account connection resource) in Active Directory but I am still facing the above privileges issue.
According to some test, you need to add the permissions of Azure AD but not Micorsoft Graph. It seems the Get-AzureADUser command use Azure AD graph in the backend. So we need to do the operations as below:
After that we can use the command Get-AzureADUser successfully(if you test the command in powershell, when you add the Azure AD permission, please close the powershell and reopen it and re-connect)
I'm trying to automate Azure resource creation using out-of-the-box Terraform via Azure DevOps, but for some parts I need Powershell. That's fine, as there is this local-exec thing I can use.
The Powershell scripts work fine when I run them locally on Terraform, but running everything from Azure DevOps I get this login error: Run Connect-AzAccount to login
I have a DevOps service principal running the release definition, but it seems the context of the Terraform process is not propagated to the execution of the Powershell script?
I don't want to extract the Powershell stuff from the Terraform script, to run it as a separate DevOps task as this is one of the sequence steps of my deployment.
What can I do to make this work?
I'm not sure whose task you are using for Terraform, but I am able to do the following in my externally called PowerShell script:
$subscriptionId = $env:ARM_SUBSCRIPTION_ID
$tenantId = $env:ARM_TENANT_ID
$clientId = $env:ARM_CLIENT_ID
$secret = $env:ARM_CLIENT_SECRET
I'm using the az cli, so I then run this command
az.cmd login --service-principal --username $clientId --password $secret --tenant $tenantId --output none
But you should be able to also run:
$securesecret = ConvertTo-SecureString -String $secret -AsPlainText -Force
$Credential = New-Object pscredential($clientId,$securesecret)
Connect-AzAccount -Credential $Credential -Tenant $tenantId -ServicePrincipal
Select-AzSubscription $subscriptionId
I am trying to automate the process of an Azure Active Directory (AAD) app registration using Azure DevOps release pipeline but it fails to do so. (Please note that the same command (powershell commands as well as azure commands) works perfectly fine if I am running the same commands from my laptop) and for that I created an azure powershell task in the release pipeline and used the following line of code in the "inline script section":
I tried creating the AAD app registration using the following 2 methods:
1. "Azure Powershell script task"
2. Azure commands
Following is inline script that I used in case of azure powershell task:
Import-Module AzureRM
Import-Module AzureAD
# Register an AAD app
$appURI = "https://knaabdapp123.azurewebsites.net"
$appHomePageUrl = "https://knaabdapp123.knandan.in"
$appReplyURLs = #($appURI, $appHomePageURL, "https://localhost:12345")
New-AzureADApplication -DisplayName knaabdapp123 -IdentifierUris $appURI -Homepage $appHomePageUrl -ReplyUrls $appReplyURLs
I get the following error when I do so:
2019-08-09T11:27:31.1039145Z ##[section]Starting: Azure PowerShell script: Register an AAD app and generate credential for the same
2019-08-09T11:27:31.1162119Z ==============================================================================
2019-08-09T11:27:31.1162226Z Task : Azure PowerShell
2019-08-09T11:27:31.1162310Z Description : Run a PowerShell script within an Azure environment
2019-08-09T11:27:31.1162378Z Version : 2.153.1
2019-08-09T11:27:31.1162446Z Author : Microsoft Corporation
2019-08-09T11:27:31.1162520Z Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-powershell
2019-08-09T11:27:31.1162620Z ==============================================================================
2019-08-09T11:27:37.0179906Z ##[command]Import-Module -Name C:\Modules\AzureRm_5.1.1\AzureRM\5.1.1\AzureRM.psd1 -Global
2019-08-09T11:28:10.7554409Z ##[command]Clear-AzureRmContext -Scope Process
2019-08-09T11:28:11.2755157Z ##[command]Disable-AzureRmContextAutosave -ErrorAction Stop
2019-08-09T11:28:15.0230853Z ##[command]Add-AzureRMAccount -ServicePrincipal -Tenant *** -Credential System.Management.Automation.PSCredential -Environment AzureCloud #processScope
2019-08-09T11:28:16.5226685Z ##[command] Select-AzureRMSubscription -SubscriptionId a*******-ae1c-****-****-********** -TenantId ***
2019-08-09T11:28:16.8648715Z ##[command]& 'C:\Users\VssAdministrator\AppData\Local\Temp\2a55****-67c6-****-8f80-**********.ps1'
2019-08-09T11:28:17.0308219Z ##[error]The specified module 'AzureAD' was not loaded because no valid module file was found in any module directory.
2019-08-09T11:28:19.0607544Z ##[command]Remove-AzureRmAccount -Scope Process -ErrorAction Stop
2019-08-09T11:28:19.4371114Z ##[command]Clear-AzureRmContext -Scope Process -ErrorAction Stop
2019-08-09T11:28:19.8885329Z ##[error]The term 'New-AzureADApplication' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I also used the Azure CLI task and used the following script, but that fails too:
az ad app create --display-name MyApplication123 --homepage "https://myapplication1232.nl" --reply-urls "https://localhost:12345" --identifier-uris "https://myapplication2.azurewebsites.net"
I get the following error in this case:
>az ad app create --display-name MyApplication123 --homepage "https://myapplication1232.nl" --reply-urls "https://localhost:12345" --identifier-uris "https://myapplication2.azurewebsites.net"
2019-08-09T11:47:46.5676945Z ERROR: Insufficient privileges to complete the operation.
2019-08-09T11:47:46.6721317Z ##[error]Script failed with error: Error: d:\a\_temp\azureclitaskscript1565351201021.bat failed with return code: 1
So, I have 2 questions:
Is it possible to create an AAD app registration using "Azure powershell" task script or "Azure CLI" task in Azure DevOps?
If yes, then what may I be doing wrong?
Is it possible to create an AAD app registration using "Azure
powershell" task script or "Azure CLI" task in Azure DevOps?
For this question, the answer is Yes, of course you can.
The cause of the error you received in Azure Powershell task is as default, the AzureAD powershell cmdlets will not be installed in agent.So, if you try to using this module directly, you will receive the message like "##[error]The specified module 'AzureAD' was not loaded because no valid module file was found in any module directory."
If yes, then what may I be doing wrong?
To solve this error message, please try with replacing your script Import-Module AzureAD as the follow script to use a correct way to get the AzureAD module.
$AzureADModulePath = $PSScriptRoot + "\AzureAD\2.0.1.16\AzureAD.psd1"
Import-Module $azureAdModulePath
This is the detailed info about AzureAD module in Powershell Gallery. And also, here has a blog you can refer.
Updated:
You must install AzureAD cmdlets module from the PowerShell gallery with the below script first:
Install-Module -Name AzureAD -RequiredVersion 2.0.1.16
Note: If get error like Install-Module : Administrator rights are required to install modules while you install with this script, please add -scope CurrentUser to the install script. It will running the script as administrator role.
And then, import the module from the installed path afterwards.
Trying to perform an az cli login using a Service Principal and it is throwing an error stating No subscriptions found for <Service_Principal_AppId>. If this is expected, use '--allow-no-subscriptions'. This code has worked fine previously but now it does not appear to work any longer. Command line being used is below:
$sp_appid = (Get-AzureRmADServicePrincipal -DisplayName $spDisplayName).ApplicationId.Guid
$sp_secret = (Get-AzureKeyVaultSecret -VaultName $kvName -Name $appKeySecretName).SecretValueText
az login --service-principal --username $sp_appid --password $sp_secret --tenant $tenant_Id
I verified that the Service Principal is assigned the Contributor role at the subscription level.
After creating a service principal in the Azure Active Directory you need to give this new user some roles within a subscription:
go to your subscription
go to Access Control (IAM)
Add a roles assignment (for instance make your service principal contributor)
Then az login should work.
Actually, I don't recommend you to mix the Azure Powershell and CLI together. If you insist on doing it, I have tried your script, I could not reproduce your issue, it works fine.
According to the error, you could try to pass a --subscription, it also works.
$sp_appid = (Get-AzADServicePrincipal -DisplayName joywebapp2).ApplicationId.Guid
$sp_secret = (Get-AzKeyVaultSecret -VaultName joykeyvault1 -Name joywebapp2).SecretValueText
$tenant_Id = "xxxxxxxxxxxx"
$subscription_Id = "xxxxxxxxxxx"
az login --service-principal --username $sp_appid --password $sp_secret --tenant $tenant_Id --subscription $subscription_Id
Note: Due to the AzureRM powershell module has been deprecated, I use the new Az powershell module, if you want to upgrade to Az, see this link. (It may not be the reason of the issue, but I recommend you to upgrade it.)
Update:
We have to use AZ CLI simply for the property we are trying to grab...there is no PowerShell equivalent.
Actually you can login with a service principal via powershell, the strong password is the secret, more details see this post.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
The original problem appears to have been a transient platform problem. Went back to the same code yesterday and it work with no issues.
For me, running cache purge worked:
az cache purge
Also, if it still does not work try printing verbose information using:
az login --verbose
I had the same issue that suddenly no subscriptions where showing up for my service principal (on 2 different build servers that I originally installed at the same time).
Updating the Azure CLI seemed to fix the issue.
Trying to az login with a Service Principal account, which does not have Role Based Access Control in its Subscription Scope, will fail with ERROR: No subscriptions found.
Moreover in recent Azure CLI, using the login command with the subscription flag would return unrecognized arguments: --subscription
Thus, to login without specifying subscription, make sure to add a role to your Service Principal account:
# Authenticate via browser
az login
# Get current subscription
subscriptionID=$(az account show --query id -o tsv)
# Create/update servie account with a role (e.g. "Owner")
az ad sp create-for-rbac --name ${theServiceAccount} --role Owner --scopes /subscriptions/${subscriptionID}
# Get current tenant
tenantID=$(az account show --query tenantId -o tsv)
# Login with the updated service account
az login --service-principal --tenant ${tenantID} -u yourUser -p yourPassword