Azure Automation Variables - azure

I am trying to make a code using PowerShell so that secrets are not hardcoded on my runbook so that it will not be exposed in the script. I created encrypted variables in my automation account. These variables are AppID, AppSecret and TenantID.
This is the part of the script to login automatically to Azure. I didn't use managed identity for some compatibility reasons with the script.
My script is running fine when secrets and IDs are hardcoded but when I created variables it is not working. Error message is "Run Connect-AzAccount". Below is my code. Need help on how to correct this. Thank you in advance.
$AzVariableApplicationID = 'AppID'
$AzVariableAppSecret = 'AppSecret'
$AzVariableTenantID = 'TenantID'
$AppID = Get-AzAutomationVariable -Name $AzVariableApplicationID
$AppSecret = Get-AzAutomationVariable -Name $AzVariableAppSecret
$TenantID = Get-AzAutomationVariable -Name $AzVariableTenantID
$SecureSecret = $AppSecret | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $AppID, $SecureSecret
Connect-AzAccount -ServicePrincipal -Credential $Credential -Tenant $TenantID

As described in PsCustom Object - Hitchikers GUID(e) to Automation
, It is not possible to retrieve values for encrypted variables as they’re available within the runbook at runtime via the Get-AutomationVariable cmdlet
I found an alternative approach to "Connect Azure" by using "Certificate-based authentication" inside PowerShell runbook without hardcoding the values:
Created a new Service principal and provided the "Owner" role access to avoid any restrictions.
To authenticate via service principal, I create a new self-signed certificate with the command:
$cert=New-SelfSignedCertificate -Subject "CN=xxxxxCert" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature
Upload a certificate under Certifications & Secrets:
Click windows + R to open the run box and give certmgr.msc as shown here.
Export a certificate without private key.
Upload a certificate in the below path:
AzureAD -> App registrations -> Serviceprincipal
Now, I have exported the same certificate with key and uploaded inside my automation account to authenticate Service principal connection:
Added an "Azure Service Principal" connection inside automation accounts by providing "ApplicationID, TenantID, Certificate Thumbprint" of my Service principal as shown:
Inside PowerShell runbook, I ran the below script that works for me:
$connectionName = "serviceprincipalname"
try
{
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRMAccount
-ServicePrincipal `
-TenantID $servicePrincipalConnection.TenantID `
-ApplicationID $servicePrincipalConnection.applicationID `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found. "
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
Logged in to Azure:
Register an App in App registrations and create a service principal in AzureAD

Related

Azure Connect-AzAccount in runbook with managed identity fails

I am trying to execute a runbook in an automation account within azure.
I have set a managed identity following the instructions here, then i issue the following in my runbook:
Connect-AzAccount -Identity
Set-AzContext -Subscription Subscription1
As instructed here
But i get the following error:
Set-AzContext : Please provide a valid tenant or a valid subscription.
At line:134 char:1
+ Set-AzContext -Tenant $tenantId -Subscription $subscriptionId
I pass the tenantId and subscriptionId through as parameters, and have written them out to confirm they are correct.
Can anyone see where I am going wrong?
Update
I have added the owner role to the system assigned managed identity and now it seems to get the connection ok with Dilly B's suggestion below:
$null = Disable-AzContextAutosave -Scope Process # Ensures you do not inherit an AzContext in your runbook
$AzureContext = (Connect-AzAccount -Identity -AccountId $managedIdentity).context # Connect to Azure with user-assigned managed identity
$connectionResult = Set-AzContext -Subscription $subscriptionId -DefaultProfile $AzureContext
however when i do:
$virtualMachine = Get-AzVM -ResourceGroupName $resourceGroupName -Name $virtualMachineName
I now get the following error:
Get-AzVM : The client '****************' with object id '*****************' does
not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/******************/resourceGroups/***************/providers/Microsoft.Compute/virtualMachines/************' or the scope is invalid. If access was recently granted, please refresh your credentials.
ErrorCode: AuthorizationFailed
ErrorMessage: The client '******************' with object id '*****************************'
does not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/******************/resourceGroups/**************/providers/Microsoft.Compute/virtualMachines/**************' or the scope is invalid.
Please find the sample code below. Hope this helps!
$subscription = "000000-0000-0000-0000-000000000"
$identity = "000000-0000-0000-0000-000000000"
$null = Disable-AzContextAutosave -Scope Process # Ensures you do not inherit an AzContext in your runbook
$AzureContext = (Connect-AzAccount -Identity -AccountId $identity).context # Connect to Azure with user-assigned managed identity
$connectionResult = Set-AzContext -Subscription $subscription -DefaultProfile $AzureContext
Make sure you have up-to-date modules for Az.Accounts (2.10.2), Az.Resources (6.3.0), Az.Automation (1.8.0).
https://learn.microsoft.com/en-us/azure/automation/automation-update-azure-modules

Restart-AzAnalysisServicesInstance : Response status code does not indicate success: 401 (Unauthorized)

I have an Azure Analysis Services with S1 SKU. There is an SPN who has OWNER RBAC over the AAS. I am trying to use a PowerShell 5.1 Runbook through an Automation Account to run the Restart-AzAnalysisServicesInstance cmdlet.
When I run the Runbook, I get to see the error:
Restart-AzAnalysisServicesInstance : Response status code does not indicate success: 401 (Unauthorized).
However, when I run the cmdlet locally, using my credentials to Connect-AzAccount in Windows Powershell ISE, it works. I am also an OWNER over the AAS.
Here's the Runbook:
# Init
$ErrorActionPreference = 'Stop'
$AutomationAccountConnectionName = "Name of my Connection that uses the Owner SPN"
# Get Automation connection (SPN connection details)
$servicePrincipalConnection = Get-AutomationConnection -Name $AutomationAccountConnectionName
Write-Output "Connected using SPN:"
$servicePrincipalConnection
# Connect using SPN
Write-Output "Connecting to AZ using the SPN connection:"
$Connection | ConvertTo-Json
$azContext = Connect-AzAccount -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-Tenant $servicePrincipalConnection.TenantId -ServicePrincipal
Write-Output ("Connected to azure using certificate with app id : " + $Connection.AppId)
# Get AAS
$aasServer = "test113aas"
$subscriptionId = "GUID of my azure subscrition"
Select-AzSubscription -Subscription $subscriptionId
$resourceObj = Get-AzAnalysisServicesServer -Name $aasServer
$ResourceObj
$AnalysisServer = $resourceObj.Name
$AnalysisServerLocation = 'northeurope'
$ModelName = 'adventureworks'
# # Connect AAS Account => This did not help as well
# Write-Host "Adding AAS Account"
# Add-AzAnalysisServicesAccount -RolloutEnvironment "$AnalysisServerLocation.asazure.windows.net" `
# -ServicePrincipal -ApplicationId $servicePrincipalConnection.ApplicationId `
# -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint -TenantId $servicePrincipalConnection.TenantId
# Restart AAS server
Write-Host "Server's full name is $($resourceObj.ServerFullName)"
Write-Host "$AnalysisServer : Preparing to Restart the Analysis Server"
$result = Restart-AzAnalysisServicesInstance –Instance $resourceObj.ServerFullName -PassThru # returns true if successful
$result
Any idea as to what I am missing out here? Documentation: https://learn.microsoft.com/en-us/powershell/module/az.analysisservices/restart-azanalysisservicesinstance?view=azps-7.2.0
I even tried running the same within an Azure PowerShell Core Function, since the documentation is for PowerShell 7+, but to no avail.
Turns out that we need to whitelist the client's IP before calling the cmdlet.
The error message could have been more precise.

Connect-AzAccount with Azure Devops Pipeline?

I am finding difficulties in finding the best and secure way to use connect-azaccount with azure devops pipeline. I have in the pipeline the following this simple powershell script which is used to create azure resources. Just to simplify things I only used the creation of a resource group:
$Location = "Location Name"
$resourceGroupName = "Resource Group Name"
try {
#Creation of Resource Group
$resourceGroup = Get-AzResourceGroup -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
if($null -eq $resourceGroup)
{
New-AzResourceGroup -Name $resourceGroupName -Location $Location
}
else
{
Write-Host "The ResourceGroup with the name: $resourceGroupName already exists."
}
}
catch
{
Write-Host "Error occurred: $_"
}
The problem here is when the pipeline is being run and it reaches the Powershell task, it gives me an error, Error occurred: Run Connect-AzAccount to login.
My issue here is that I honestly don't know which way is the most secure way to connect without typing any user credentials. It should directly connect and create the resources. Note that I am using Multi-Factor Authentication. In order to achieve that I found several solutions but I need help in choosing the best way. I found several solutions by adding a powershell task in the Yaml file. Here is the Yaml showing the powershell task to run the script:
- task: PowerShell#2
inputs:
filePath: '$(Pipeline.Workspace)/Deploy/functionapp.ps1'
Option 1:
Connect-AzAccount -Tenant 'xxxx-xxxx-xxxx-xxxx' -SubscriptionId 'yyyy-yyyy-yyyy-yyyy'
Now the problem here is that the Tenant ID and Subscription are going to be visible in the code and that is a very bad practice
Option 2 is to use the following script:
$User = "xxx#xxxx.onmicrosoft.com"
$PWord = ConvertTo-SecureString -String "<Password>" -AsPlainText -Force
$tenant = "<tenant id>"
$subscription = "<subscription id>"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
Connect-AzAccount -Credential $Credential -Tenant $tenant -Subscription $subscription
This is very similar to the first, but if I am not mistaken it is limited to a specific user.
Option 3 is to use a service principal:
$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)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
I don't know if creating a service principal will incur any costs and what steps should I do to make it work.
I am honestly new to all this, can someone please provide me what are the exact steps to achieve this. Thank you for your answers :)
The most secure way is to create an Azure Resource Manager service connection and use it in your pipeline. You can create it using automated way, or manually using previously created service principal.

New-AzureRmRoleAssignment : Object reference not set to an instance of an object

Unable to assign role to user using New-AzureRmRoleAssignment command. When I run the above command its thronging an error as follows .
New-AzureRmRoleAssignment : Object reference not set to an instance of an object.
Can any one help to resole the issue.
To assign role to user successfully in the runbook, follow the steps below.
Note : The New-AzureRmRoleAssignment you used belongs to the old AzureRM, it was deprecated and will not be updated anymore. In my sample, I use the new Az command New-AzRoleAssignment, I also recommend you to use it.
1.Navigate to the subscription in the portal(you need to be Owner/User Access Administrator in the subscription) -> add the service principal of your automation RunAs account as an Owner/User Access Administrator(by default it will be added as Contributor when it was created, but Contributor have no permission to run New-AzRoleAssignment).
2.Navigate to the Azure Active Directory in the portal -> App registrations -> find the AD App of your RunAs Account and add the Directory.Read.All application permission in Azure Active Directory Graph(Not Microsoft Graph) like below, don't forget to click the Grant admin consent for xxx button at last(you need to be the admin role in your AAD tenant). The permission may take about 30 min to take effect.
3.Navigate to the automation account in the portal -> Modules -> make sure you have installed the Az.Accounts, Az.Resources modules, if not, go to Browse Gallery, search for the names, and install them.
4.Then in the runbook, use the script below, it works fine on my side. In my sample, I add the user as a Reader in the resource group joyRG, you can change it, it depends on your requirement.
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$user = Get-AzADUser -UserPrincipalName joyw2#xxxx.onmicrosoft.com
New-AzRoleAssignment -ObjectId $user.id -ResourceGroupName joyRG -RoleDefinitionName Reader

login to azure account without popup using powershell

I'm trying to create Azure VM using powershell.I have also the script to create it.
First I need to login into Azure account :
Login-AzureRMAccount
This gives a pop-up to enter the credentials.
Second I need to run the below script:
$UserName = "username"
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-AzureRmVm `
-ResourceGroupName "RG1" `
-Name "VM1" `
-ImageName "Image1" `
-Location "West US" `
-Credential $psCred
This is creating the VM successfully.
But now , I need to make these scripts run automatically, when ever there is requirement. The problem I'm facing is, the login step gives a popup to enter the credentials which I do not want. So I have tried something like this, but didn't work.
$username = "loginname#organization.com"
$SecurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
Login-AzureRmAccount -Credential $cred
The error message it is giving is :
Login-AzureRmAccount : accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed: The underlying connection was closed: An unexpected error occurred on a send.
At line:4 char:1
+ Login-AzureRmAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
Can anyone tell me what this means and how to rectify this? Thanks!
If you are planning to automate any services into Azure using PowerShell, then I'd recommend connecting azure using Service Principal rather than your own credentials, it will be a secure way to connect.
What is Service principal?
An Azure service principal is a security identity used by user-created
apps, services, and automation tools to access specific Azure
resources. Think of it as a 'user identity' (username and password or
certificate) with a specific role, and tightly controlled permissions.
It only needs to be able to do specific things, unlike a general user
identity. It improves security if you only grant it the minimum
permissions level needed to perform its management tasks.
Follow this tutorial to create a service principal
I also have published a sample PowerShell workflow into Microsoft gallery for creating Service Principal you can also follow that.
Once you created your service principal, you can use the below PowerShell commands to login into azure without any popup's
$applicationId = "<service prinicple application id>";
$securePassword = "<service prinicple password>" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -TenantId "<your tenantid>"
Update1:
For some reason/bug the above will get fails. Refer this github issue
To solve this
Add the two lines before the script
Import-Module -Name AzureRM.Profile
Remove-AzureRmAccount
Update 2:
AzureRM will no longer receive new cmdlets or features. However, the AzureRM module is still officially maintained and will get bug fixes through December 2020.
You have to use the new Azure PowerShell Az module
Basically you can achieve this for all of your PowerShell sessions by adding the Logging in part as part of the $PSProfile. I use this trick to skip the login popup, so whenever i open powershell my account is automatically logged in.
Open Windows PowerShell as an administrator
Type Notepad $profile
A notepad file will be opened and here you can paste the below code to
log in automatically whenever it is opened.
$username = “”
$password = “”
$securepasswd = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($username, $ securepasswd)
Connect-AzureRmAccount -Credential $cred

Resources