Unable to change active subscription in yaml/Azure PowerShell pipeline - azure-devops

This is kind of continuation of the issue I faced in here
Let me give a backgroud. This is my yaml pipleine:
parameters:
- name: sub_name # name of the subscription; required
type: string
default: false
steps:
- script: echo "Here is subscription name:" ${{ parameters.sub_name }}
- task: AzurePowerShell#5
displayName: 'Launching Main.yml'
inputs:
azurePowerShellVersion: LatestVersion
azureSubscription: My-SPN # This is my almighty Service Principal
ScriptType: 'FilePath'
ScriptPath: '$(System.DefaultWorkingDirectory)/MyPowerShell.ps1'
ScriptArguments: -sub_name ${{ parameters.sub_name }}
and this is my MyPowerShell.ps1 file:
#param ($sub_name)
Get-AzContext -ListAvailable | Where{$_.Name -match $sub_name} | Set-AzContext
$SID=(Get-AzContext).Subscription.id
Write-Output "The active subscription SID is" $SID
No matter what value the $sub_name is given the output of $SID is always the Subscription Id of my service principal - "My-SPN"
How should I set AzContext properly so it changes active subscription?
The same PowerShell script works fine in Azure CLI but not when yaml has got service principal.
I tried to use Set-AzContext -Subscription $sub_name -TenantId 2a1c169e-715a-412b-b526-05da3f8412fa but ended up with following error:
Starting: Launching Main.yml
==============================================================================
Task : Azure PowerShell
Description : Run a PowerShell script within an Azure environment
Version : 5.209.0
Author : Microsoft Corporation
Help : https://aka.ms/azurepowershelltroubleshooting
==============================================================================
Generating script.
========================== Starting Command Output ===========================
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a_temp\adfb7562-7db5-4be6-ae08-dca4664e460c.ps1'"
Added TLS 1.2 in session.
Import-Module -Name C:\Modules\az_7.5.0\Az.Accounts\2.9.1\Az.Accounts.psd1 -Global
WARNING: Both Az and AzureRM modules were detected on this machine. Az and AzureRM modules cannot be imported in the
same session or used in the same script or runbook. If you are running PowerShell in an environment you control you can
use the 'Uninstall-AzureRm' cmdlet to remove all AzureRm modules from your machine. If you are running in Azure
Automation, take care that none of your runbooks import both Az and AzureRM modules. More information can be found
here: https://aka.ms/azps-migration-guide
Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
Clear-AzContext -Scope Process
Connect-AzAccount -ServicePrincipal -Tenant 2a1c169e-715a-412b-b526-05da3f8412fa -Credential System.Management.Automation.PSCredential -Environment AzureCloud #processScope
Set-AzContext -SubscriptionId 72245732-XXXXXXX -TenantId 2a1c169e-XXXXXXXX
##[error]Please provide a valid tenant or a valid subscription.
##[error]PowerShell exited with code '1'.
Added TLS 1.2 in session.
Finishing: Launching Main.yml
Please help on how to change an active subscription either in a yaml or in powershell file.
Thanks.

AzurePowerShell task uses Service Principal to authenticate and access Azure resources. Therefore, your service principal needs to have subscription owner or contributor permission.

Like #ZiyangLiu-MSFT mentioned above the service principal I was using hasn't had enough rights on the subscription. Changed it to the one which have had proper permission and this resolved the issue.

Related

Copy build artifacts to Azure Blob Storage

I am using the Azure File Copy tasks in DevOps to copy the artifacts from Git to a Blob storage that sits under my subscription:
However the Azure File Copy tasks never completes. The task continues to run. I'm wondering if it's because of permission issue where my subscription can't write to the Blob storage. Is there something I'm doing wrong?
steps:
- task: AzureFileCopy#5
displayName: 'AzureBlob File Copy'
inputs:
SourcePath: '$(System.DefaultWorkingDirectory)/_ADF-MRSG-Tide-Continuous-Integration-Build/ArmTemplates'
azureSubscription: 'BDAP-PRD-PIPELINE-CONN (xxxxxxxx)'
Destination: AzureBlob
storage: mrsgtideprdwedev
ContainerName: 'azure-artifacts'
EDIT
Log information:
2023-01-12T17:01:15.4423974Z ##[section]Starting: AzureBlob File Copy
2023-01-12T17:01:15.4550000Z ==============================================================================
2023-01-12T17:01:15.4550253Z Task : Azure file copy
2023-01-12T17:01:15.4550388Z Description : Copy files to Azure Blob Storage or virtual machines
2023-01-12T17:01:15.4550590Z Version : 5.210.1
2023-01-12T17:01:15.4550713Z Author : Microsoft Corporation
2023-01-12T17:01:15.4550863Z Help : https://docs.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-file-copy
2023-01-12T17:01:15.4551268Z ==============================================================================
2023-01-12T17:01:20.7123632Z ##[command]Import-Module -Name C:\Modules\az_9.0.1\Az.Accounts\2.10.4\Az.Accounts.psd1 -Global
2023-01-12T17:01:22.8437792Z ##[warning]Both Az and AzureRM modules were detected on this machine. Az and AzureRM modules cannot be imported in the same session or used in the same script or runbook. If you are running PowerShell in an environment you control you can use the 'Uninstall-AzureRm' cmdlet to remove all AzureRm modules from your machine. If you are running in Azure Automation, take care that none of your runbooks import both Az and AzureRM modules. More information can be found here: https://aka.ms/azps-migration-guide
2023-01-12T17:01:31.6898708Z ##[command]Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
2023-01-12T17:01:32.5179394Z ##[command]Clear-AzContext -Scope Process
2023-01-12T17:01:32.5180271Z ##[command]Connect-AzAccount -ServicePrincipal -Tenant xxx -Credential System.Management.Automation.PSCredential -Environment AzureCloud #processScope
2023-01-12T17:01:35.1239900Z ##[command] Set-AzContext -SubscriptionId xxx -TenantId xxx
2023-01-12T17:01:36.0411697Z ##[command]Import-Module -Name C:\Modules\az_9.0.1\Az.Resources\6.3.1\Az.Resources.psd1 -Global
2023-01-12T17:01:39.1422423Z ##[command]Import-Module -Name C:\Modules\az_9.0.1\Az.Storage\5.0.0\Az.Storage.psd1 -Global
2023-01-12T17:01:41.0099745Z ##[command]Import-Module -Name C:\Modules\az_9.0.1\Az.Compute\5.0.0\Az.Compute.psd1 -Global
2023-01-12T17:01:44.7529810Z ##[command]Import-Module -Name C:\Modules\az_9.0.1\Az.Network\5.0.0\Az.Network.psd1 -Global
2023-01-12T17:01:45.5713749Z ##[warning]The names of some imported commands from the module 'Microsoft.Azure.PowerShell.Cmdlets.Network' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.
2023-01-12T17:01:45.8587032Z ##[warning]The names of some imported commands from the module 'Az.Network' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.
2023-01-12T17:11:24.8085548Z ##[command]Disconnect-AzAccount -Scope Process -ErrorAction Stop
2023-01-12T17:11:24.8364623Z ##[command]Clear-AzContext -Scope Process -ErrorAction Stop
2023-01-12T17:11:24.9976554Z ##[error]This request is not authorized to perform this operation.
RequestId:0e6ffe85-601e-0047-3da8-2639da000000
Time:2023-01-12T17:11:24.5146395Z
Status: 403 (This request is not authorized to perform this operation.)
ErrorCode: AuthorizationFailure
Content:
<?xml version="1.0" encoding="utf-8"?><Error><Code>AuthorizationFailure</Code><Message>This request is not authorized to perform this operation.
RequestId:0e6ffe85-601e-0047-3da8-2639da000000
Time:2023-01-12T17:11:24.5146395Z</Message></Error>
Headers:
x-ms-request-id: 0e6ffe85-601e-0047-3da8-2639da000000
x-ms-client-request-id: 069ac45e-6638-4d55-9ece-39522ed6f5c5
x-ms-error-code: AuthorizationFailure
Content-Length: 246
Content-Type: application/xml
Date: Thu, 12 Jan 2023 17:11:24 GMT
Server: Microsoft-HTTPAPI/2.0
2023-01-12T17:11:25.0733282Z ##[section]Finishing: AzureBlob File Copy

Azure Powershell: Unable to find environment with name 'AzureCloud' on self-hosted azure devops agent

I have suddenly started getting this error on some of the agents that are installed on my Agent Pool. All of them are on the same Virtual Machine:
2022-06-13T11:07:24.5665998Z ##[command]"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\Agent\02\_work\_temp\3c5c143c-117b-4adb-9c90-7043632edfa0.ps1'"
2022-06-13T11:07:26.0076950Z Added TLS 1.2 in session.
2022-06-13T11:07:26.1347095Z ##[command]Import-Module -Name C:\Program Files\PowerShell\Modules\Az.Accounts\2.8.0\Az.Accounts.psd1 -Global
2022-06-13T11:07:26.8410918Z ##[command]Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
2022-06-13T11:07:27.4110901Z ##[command]Clear-AzContext -Scope Process
2022-06-13T11:07:27.4789914Z ##[command]Connect-AzAccount -ServicePrincipal -Tenant {{Redacted}} -Credential System.Management.Automation.PSCredential -Environment AzureCloud #processScope
2022-06-13T11:07:27.5295739Z ##[error]Unable to find environment with name 'AzureCloud'
2022-06-13T11:07:27.6855841Z ##[error]There was an error with the service principal used for the deployment.
2022-06-13T11:07:27.7936958Z ##[error]PowerShell exited with code '1'.
2022-06-13T11:07:29.5169529Z ##[command]Disconnect-AzAccount -Scope Process -ErrorAction Stop
2022-06-13T11:07:29.9206643Z ##[command]Clear-AzContext -Scope Process -ErrorAction Stop
I have tried uninstalling and installing azure powershell, but the error persist. Also agents which are using the same service connection on a different VM are deploying without any issues.
Finally I tried to run the command locally on my VM and it succeeded, so I am not sure what could be causing this error.
From the error message, it may cause by Azure PowerShell Module.
You could try uninstall the Az PowerShell module locally on your VM : https://learn.microsoft.com/en-us/powershell/azure/uninstall-az-ps?view=azps-8.0.0
And re-install for "AllUsers" scope:
Install-Module -Name Az -Scope AllUsers -Repository PSGallery -Force

Azure Devops powershell release pipeline strange chars

I have prepared a release pipeline in Azure Devops.
The pipeline has a powershell task.
This is the inline code.
Install-Module -Name Az -AllowClobber -Force
Install-Module -Name Bicep -Force
Import-Module Az.Accounts -Force
$PSVersionTable
This is the log output:
"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -NoProfile
-NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a_temp\67e051fe-1dd4-4420-b9c0-577a882c1207.ps1'"
[33;1mWARNING: Both Az and AzureRM modules were detected on this
machine. Az and AzureRM modules cannot be imported in the same session
or used in the same script or runbook. If you are running PowerShell
in an environment you control you can use the 'Uninstall-AzureRm'
cmdlet to remove all AzureRm modules from your machine. If you are
running in Azure Automation, take care that none of your runbooks
import both Az and AzureRM modules. More information can be found
here: https://aka.ms/azps-migration-guide[0m
[32;1mAccount SubscriptionName
TenantId Environment[0m [32;1m-------
---------------- -------- -----------[0m
*** xxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx AzureCloud [32;1mName : [0mxxxxxx (xxxxxxxxxxxxxxxxxxxx) -
xxxxxxxxxxxxxxxxxxxx -
[32;1m[0m*** [32;1mAccount : [0m*** [32;1mEnvironment : [0mAzureCloud [32;1mSubscription
: [0mxxxxxxxxxxxxxxxxxxxxxx [32;1mTenant :
[0mxxxxxxxxxxxxxxxxxxxxxx [32;1mTokenCache : [0m
[32;1mVersionProfile : [0m [32;1mExtendedProperties : [0m{}
Two questions:
what's wrong with characters?
what does it means this "Both Az and AzureRM modules were detected on this machine" and hot to fix it?
I searched for something but i'm confused and not able to distinguish between various things I have found.
Thanks in advance for helping me.
This is due to the newer versions of pwsh using ANSI to colour code the terminal.
You can disable it as part of your pipeline task too
More here:
Powershell - disable colored command output

Access Denied on Powershell Start-Process within AzureDevOps task

I have an Azure DevOps task which needs to execute a Powershell script on a VM. The inline script generates a credential which is used as a parameter for the Powershell process being started.
- task: AzureCLI#2
inputs:
azureSubscription: 'MySubscription'
scriptType: 'ps'
scriptLocation: 'inlineScript'
inlineScript: |
az vm run-command invoke --command-id RunPowerShellScript --name $(MyVmName) -g My-RG --scripts `
"`$pw = ConvertTo-SecureString `"$(PasswordSecret)`" -AsPlainText -Force" `
"`$cred = New-Object System.Management.Automation.PSCredential 'Vm1\localadmin',`$pw" `
"Start-Process PowerShell -Cred `$cred -ArgumentList '-noexit','-File','C:\Users\localadmin\Documents\deploy.ps1'"
However, it appears that the Start-Process itself is getting Access Denied:
2021-04-21T22:15:29.6078202Z "message": "Start-Process : This command cannot be run due to the error: Access is denied.\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\1.1.8\\Downloads\\script11.ps1:3 char:1\n+ Start-Process PowerShell -Cred $cred -ArgumentList '-noexit','-File', ...\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException\n + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand"
The inline script below can be found on the vm and executed successfully using the same credentials that are used to generated the $cred. But, I'm guessing that since the DevOps task is running under a different, less privileged account, it doesn't have access to the Start-Process cmdlet.
Is there a way around this?
(Note: for several reasons beyond the scope of this post, I can't use the Powershell on Target Machines task, but I have in fact tried that.)
Are you running as a hosted agent? Are you using a deployment pool?
What I've tried is setting the local deployment agent service credentials on the machine- the service has a name like Azure Pipelines Agent. You can configure a Log On As account in the services pane and restart the service to enable the agent to run as that account.
This isn't a full answer but I can revisit and update based on your response and maybe we can figure out our problems together.
Edit: ** After a couple hours of labor I've unblocked myself by using .cmd instead of powershell. I discovered though that because the agents are running as services the .exe is not being launched unless in interactive mode. The deployment will continually 'run' while the .exe is running, otherwise. Instead of doing this, I decided to just reboot the computer using cmd and having the start up task run what I need.
Maybe your answer could be similar: place the script with the agent into the startup task, then reboot the computer and allow it to run it on it's own.

Azure Devops Connect to SharePoint Online tenant - Connect-SPOService cmdlet timing out

Been working with using Azure DevOps to automate some PowerShell scripts against SharePoint Online. From what I understand, my first step needs to be getting authenticated against that tenant. So here's what I've got so far:
trigger:
- master
pool:
vmImage: 'windows-latest'
steps:
powershell: Install-Module -Name Microsoft.Online.SharePoint.PowerShell -RequiredVersion 16.0.8029.0 -force
displayName: 'Install SP Online PowerShell'
powershell: $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $env:USERNAME, $(convertto-securestring $env:PASSWORD -asplaintext -force)
displayName: 'form the credentials var from previous vars'
powershell: Connect-SPOService -Url https://$env:ORG-admin.sharepoint.com -Credential $cred
displayName: 'connect to Tenant'
Environment variables username, password, and org are defined at the pipeline and seem to be working correctly (as in, I was getting different errors before deploying those). Now, I get to the final step and it just runs forever until I cancel it. It's as if it's getting some prompt on Connect-SPOService that, of course, I can't see, and so I can't respond to.
There are no errors to react to, just sits and spins and doesn't finish. My last error was that connect-sposervice wasn't a recognized cmdlet. To resolve that, I worked on my install-module command and got that resolved, so it seems like it's running that command properly now (no errors).
I can run all the same powershells from my local machine and get there without prompts or having to enter anything extra.
Anyone have any ideas?
Thanks!
It seems that you're following this document to connect to Sharepoint online.
Note: When prompted with the Windows PowerShell credential request dialog box, type the password for the SharePoint Online SharePoint administrator account.
When using Microsoft-hosted agent to run the PowerShell task, we can't access the UI to enter password in dislog box. So this is not supported way.
Instead, you may get help from these two documents: Installing the Office 365 CLI and Connecting to SharePoint Online.