az cli login session scope to process - powershell

In PowerShell you can do the following:
$result = Connect-AzAccount `
-SubscriptionId $SubscriptionId `
-TenantId $TenantId `
-Credential $credential `
-ContextName $contextName `
-Scope Process `
-ServicePrincipal
As per the doc, if you specify the -Scope Process the Az Context will be bound to that specific PS Process.
Determines the scope of context changes, for example, whether changes apply only to the current process, or to all sessions started by this user.
Is there any way of replicating this behaviour with az cli?
My use case
I will connect to Azure from a Jenkins job. If I start two jobs, maybe one of them will disconnect via az logout -u <user> and affect the other job.
I would like to isolate the az cli session.

I haven't personally used it yet, but according to this GitHub issue which links to this documentation, it should be possible using a process scoped environment variable.

Unfortunately, there is not such an equivalent feature as -Scope Process in Azure CLI, all the available parameters here.
https://learn.microsoft.com/en-us/cli/azure/reference-index?view=azure-cli-latest#az_login

Related

Trying to Log in to Azure in Powershell

I am following the MS guide located here and everything goes through correctly until I have to actually log in. The pop up window appears for my creds and validates them, but powershell doesn't seem to notice.
So it goes Install Module, Import Module, Verify Version, Log in. See below for what happens on the last two steps.
PS C:\WINDOWS\system32> Get-Module AzureRM -ListAvailable | Select-Object -Property Name,Version,Path
Name Version Path
---- ------- ----
AzureRM 6.3.0 C:\Program Files\WindowsPowerShell\Modules\AzureRM\6.3.0\AzureRM.psd1
PS C:\WINDOWS\system32> Connect-AzureRmAccount
Account :
SubscriptionName :
SubscriptionId :
TenantId :
Environment :
PS C:\WINDOWS\system32>
Of course, this prevents me from doing very much else with Azure from that point forward.
Edit: Issue appears on multiple workstations
I got this same issue. I have two users like many of you: the Azure user that is the "Work" account, and then the "Personal" account which is also created automatically by Office365 and Azure. I was getting the issue when I tried to use my "personal" account, in which I have some subscriptions added (delegated).
After trying lots, what worked for me was to login to the "Work" account when the "Connect-AzureRmAccount" command asks for an username/password. Then, I again use the command "Connect-AzureRMAccount", but this time I entered the personal account, and it finally worked.
Picture here
Edit: A better way I found later was this, as I manage a lot of subscriptions/tenants from a single account (delegated access):
Put the “tenantid” into a variable (you can get this ID on the Azure Portal, in my case, on the option to change directories):
How to get your tenant's IDs quickly
$tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
Login specifying the TenantId:
Login-AzureRmAccount -TenantId $tenantId
Example 2
This behavior happens when you run
Clear-AzureRMContext -Scope CurrentUser
I'm not sure why and im attempting to debug on how to fix the issue. A work around is to close the powershell window and reopen a new powershell windows that does not have this command ran.
Running the command
Enable-AzureRmContextAutosave -Scope CurrentUser
Fixed the issue for me. This will autosave your context for every powershell session. If this is not desired you can run the command
Enable-AzureRmContextAutosave -Scope Process
which will save the azure context for only the process. Otherwise you will need to handle
You can try this...
Install-Module PoweshellGet -Force
Set-ExecutionPolicy -ExicutionPolicy Remotesigned
Install-Module AzureRm
Import-Module -Name AzureRm
Login-AzureRmAccount
You can use the below link to install latest PowerShell version:
https://github.com/Azure/azure-powershell/releases
And then use something like this in order to automatically pass in the username password, and skipping the UI:
$azureAccountName ="enter username here"
$azurePassword = ConvertTo-SecureString "password here" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
Login-AzureRmAccount -Credential $psCred
Have you tried the following:
Import-Module Microsoft.Powershell.Security
$azureAccountName ="enter username here"
$azurePassword = ConvertTo-SecureString "password here" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
$decrypt = $psCred.GetNetworkCredential()
$ptpass = $decrypt.Password
Write-Output "Logging in to Azure using $azureAccountName with a password of $ptpass"
Login-AzureRmAccount -Credential $psCred
If you receive an error with this code, please comment with the entire error message.
The only thing i can think of is the below
You maybe using Azure Service Management (Azure V1 / Azure Classic) which uses a different module to Azure Resource Manager (ARM , Azure V2).
To install Azure Service Management Module:
Install-Module Azure -AllowClobber
Allowing clobber because you already have AzureRM Module installed
Import Azure Module to PowerShell:
Import-Module Azure
Logs into ASM:
Add-AzureAccount
Shows you all subscriptions
Get-AzureSubscriptions
Selects the Subscription you allocate to work within
Select-AzureSubscription
Answered something similar in the below Thread:
Login-AzureRmAccount return subscription but Get-AzureSubscription return empty
Hope this helps
You can try logging in using the Service Principal credentials.
Service principal is an application created under Active Directory to which you can apply permission rules.
$pscredential = Get-Credential
Connect-AzureRmAccount -ServicePrincipal -ApplicationId "http://my-app" -Credential $pscredential -TenantId $tenantid
Refer here for more details.

Switch-AzureRmWebAppSlot does not swap the physical site only the application settings

I have been running the following command via powershell for AZURE but all that gets swapped are the application settings:
Switch-AzureRmWebAppSlot -ResourceGroupName 'myresourcegroup' -Name 'mywebsitename' -SourceSlotName "staging" -DestinationSlotName "production" -confirm -verbose
The same thing happens when I run this command:
Switch-AzureRmWebAppSlot -ResourceGroupName 'myresourcegroup' -Name 'mywebsitename' -SourceSlotName "staging" -DestinationSlotName "production" -SwapWithPreviewAction CompleteSlotSwap -confirm -verbose
I cannot use Switch-AzureWebsite as I cannot set a default subscription with my permissions.
Using the Login-AzureRMAccount the only way I found to switch slots is as follows:
$ParametersObject = #{targetSlot = "production"}
$RGN = 'resource-group-name-'
Invoke-AzureRmResourceAction -ResourceGroupName $RGN -ResourceType Microsoft.Web/sites/slots -ResourceName website-name/staging -Action slotsswap -Parameters $ParametersObject -Verbose -force
This was hard to find, in part because many examples required you to set your Azure default subscription prior to executing Switch-AzureWebsite and the other switch only moved the configuration elements over. I am curious if anyone has a clever way to discover power shell commands or ARM template commands aside from the ones generated for deployments on Azure. Ideally, I could perform an action on Azure an then see same thing scripted as PowerShell.
REF: Microsoft Docs Here

Failure to connect to service fabric cluster from an Azure automation script

I'm trying to connect to a Azure Service Fabric cluster from an Azure Automation PowerShell Runbook. I know there's a Hybrid Runbook-approach that possibly can resolve this (c.f. this) but for reasons specific to the project I'm working on I would prefer not to use it.
Instead I have used the method described here to import the SF modules into my automation account. This makes the Connect-ServiceFabricCluster cmdlet available to me but when executed it fails to connect. I have set up a non-secure test cluster and this is the runbook code:
Import-Module "ServiceFabric" # not sure this is needed...
$connectionName = "AzureRunAsConnection"
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
"Test connecting to cluster..."
Connect-ServiceFabricCluster -ConnectionEndpoint
'[myclusterendpointurl]:19000'
"Done!"
When run in the Test-pane (or run as a regular job, doesn't matter), three attempts to execute the script is done with this logged to the output each round:
Logging in to Azure...
Environments
------------
{[AzureChinaCloud, AzureChinaCloud], [AzureCloud, AzureCloud],
[AzureGermanCloud, AzureGermanCloud], [AzureUSGovernme...
Test connecting to cluster...
until it finishes with an error:
The runbook job was attempted 3 times, but it failed each time. Common
reasons that runbook jobs fail can be found here:
https://learn.microsoft.com/en-us/azure/automation/automation-troubleshooting-automation-errors
The Connect-method just seems to time out without logging anything to the output. What goes on here?

Set-AzureRmVMCustomScriptExtension SecureExecution flag not working

We are running a custom powershell script against an Azure VM using the Set-AzureRMVMCustomScriptExtension command.
The ps script creates local user accounts provided with "username" and "password" parameters.
My understanding is that Set-AzureRMVMCustomScriptExtension supports -SecureExecution switch, which according to the documentation (https://learn.microsoft.com/en-us/powershell/module/azurerm.compute/set-azurermvmcustomscriptextension?view=azurermps-4.4.1&viewFallbackFrom=azurermps-4.4.0)
"Indicates that this cmdlet makes sure that the value of the Run parameter is not logged on the server or returned to the user by using the GET extension API. The value of Run might contain secrets or passwords to be passed to the script file securely."
However, providing the switch and executing the ps script results in the following being logged to the "Windows Powershell" event log on the target VM:
Engine state is changed from None to Available.
Details:
NewEngineState=Available
PreviousEngineState=None
SequenceNumber=13
HostName=ConsoleHost
HostVersion=5.1.14393.1770
HostId=
HostApplication=powershell -ExecutionPolicy Unrestricted -file createuser.ps1 -username myNewUser -password somePassword
EngineVersion=5.1.14393.1770
RunspaceId=
PipelineId=
CommandName=
CommandType=
ScriptName=
CommandPath=
CommandLine=
Which is not what I am expecting to see. Is this a bug? Or is the documentation incorrect?
This is the command I'm executing:
Set-AzureRmVMCustomScriptExtension -ResourceGroupName $vmResourceGroupName
-VMName $vmName
-StorageAccountName $scriptStorageAccountName
-ContainerName $scriptStorageAccountContainerName
-FileName $scriptName
-Run $scriptName
-Argument $scriptArguments
-Name $extensionAlias
-Location $location
-ForceRerun $(New-Guid).Guid
-SecureExecution
Well, its not like Azure can magically change how windows server operates. this is windows server logging, not extension logging. it won't log this to the extension log and will hide sensitive information from the api, but, obviously, powershell engine can log this input like any other input

Using AzureAD PowerShell CmdLets on TFS Release Manager

I want to execute some PowerShell scripts on our TFS Release Manager environment that use AzureAD module to provision some Azure AD groups. The scripts are executed using an Azure Powershell Task. I've installed the AzureAD module, so the AzureAD PowerShell CmdLets are recognized.
However, for them to work the scripts first needs to connect to AzureAD using the Connect-AzureAD CmdLet. This CmdLet wants to show a modal dialog for entering credentials, which obviously isn't possible in a Release Manager task. I also cannot supply credentials using command line parameters. I want Connect-AzureAD to somehow use the current user context for the connection. Is this possible?
You could use the -Credential option of Connect-AzureAD.
In your AzureAD task, you can use the following code:
```
$pass=ConvertTo-SecureString $Env:password -AsPlainText -Force
$credential=New-Object PSCredential($Env:login, $pass)
Connect-AzureAD -Credential $credential
```
login and password are stored in a secret variable in the release definition.
Alternatively you might get the password from a previous task in the build definition. I that case, in the script arguments of the task, you pass the password -password "$(password)"
and in the `Script or Script inline you have, this time:
``
param([string]$password)
$pass=ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object PSCredential($Env:login, $pass)
Connect-AzureAD -Credential $credential
``
I get the password from KeyVault with the Azure KeyVault task, but that might not be an option for you if you are on premise.
We've found an answer. It had been setting right in front of us on the official Connect-AzureAD documentation page (example 3).
So we're now authenticating using a SPN and a self-signed certificate. This works just fine.