Unattended authentication through Azure Powershell for Resource Manager - azure

I have a load of Azure Powershell deployment scripts that are triggered by the build server after the completion of a build which work perfectly - I use the Import-AzurePublishSettingsFile (which is securely stored locally) to log into Azure unattended.
I now need to extend these to include management of Sql Azure Servers, Elastic Pools and Databases.
These, however, are part of the Azure Resource Manager cmdlets which have a different method of authentication.
I've found these articles:
Authenticating a Service Principal with Azure Resource Manager
Using Azure PowerShell with Azure Resource Manager
Using Windows Azure Active Directory to Authenticate the Management Libraries)
but all appear to require you to enter your credentials at some stage at the process. The second link above explicitly states:
The AzureResourceManager module requires Add-AzureAccount. A Publish Settings file is not sufficient.
I've tried (just to see what happens) switching to the Resource Manager with Switch-AzureMode -Name AzureResourceManager and then just executing one of the cmdlets, such as Get-AzureResourceGroup -Name "blah" but I just get an error of
Get-AzureResourceGroup : AuthenticationFailed: Authentication failed. The 'Authorization' header is not present or provided in an invalid format.
I am quite happy to set up an AD Application, manually, once, through the portal and then provide my scripts with the relevant Application ID or whatever is required. I just need it to be unattended so that my build can deploy!
Can anyone tell me how I go about making an unattended script to use these Azure Resource Manager cmdlets through Powershell?

This post gives full details of how to do this. Basically you embed your powershell scripts with the username and password of your AD user.
Unattended authentication to Azure Management APIs with Azure Active Directory
But be aware that if, like me, you wish to combine calls to the AzureResourceManager and AzureServiceManagement modes (using Switch-AzureMode) then you must use Add-AzureAccount -Credential <credentials> and also Remove-AzureAccount -Name <username> otherwise some of the AzureServiceManagement mode cmdlets cease to work.

Related

Job Suspended Run Login-AzureRmAccount to login using Azure AutomationAccounts System Managed Identity

I am trying to shutdown the VM using Azure Automation Account System Managed identity option.
However I am ending up with below error.
As per the other articles it is mentioned to upgrade the module Update-ModulesInAutomationToLatestVersion but I could not update due to below error. I am not sure what is the issue in the script. Same script works with AzureRunAsConnection option without issues ( script ).I even checked with simple login with System Managed Identity it successfully login and fetches the resource group names.
I have tested the above shared script in my automation account. Below are
the couple of observations:
You need to use Connect-AzureRMAccount -Identity cmdlet instead of 'connect-AzAccount` to connect to your subscription because the rest of the script that you have written using Azure RM cmdlets.
If we use AzureRM cmdlets in your run book script the job is getting suspended stating that Azure RM is going to retired and suggesting us to use Az Module in your workflow.
You can refer to this documentation on how to migrate your PowerShell scripts automatically from AzureRM to AZ modules.
If you want to perform start/stop on your virtual Machines you can leverage the Azure Automation start/stop during the off hours feature.
According to the MICROSOFT DOCUMENTATION and looking at your script the Azure Rm module is not supported and it has been updated to the latest version of Az module.
For more information please refer the below links:-
MICROSOFT DOCUMENT|Using a system-assigned managed identity for an Azure Automation account & Troubleshoot runbook issue.

Scheduling Azure Virtual Machine (VM) Startup with Tags

I am trying to put some auto start policy on my VM on Azure.
So, I used automation account and power shell script to do this from this link: https://adamtheautomator.com/azure-vm-schedule/
But on testing it give me error of Run Login-AzureRmAccount to login
Please suggest how to fix this?
## Get the Azure Automation Acount Information
$azConn = Get-AutomationConnection -Name 'AzureRunAsConnection'
## Add the automation account context to the session
Add-AzureRMAccount -ServicePrincipal -Tenant $azConn.TenantID -ApplicationId $azConn.ApplicationId -CertificateThumbprint $azConn.CertificateThumbprint
## Get the Azure VMs with tags matching the value '10am'
$azVMs = Get-AzureRMVM | Where-Object {$_.Tags.StartTime -eq '10am'}
## Start VMs
$azVMS | Start-AzureRMVM
Regards
ESNGSRJ
This can happen when the Run As account isn't configured appropriately. You will need to create one to provide authentication for managing resources on the Azure Resource Manager using Automation runbooks.
When you create a Run As account, it performs the following tasks:
Creates an Azure AD application with a self-signed certificate, creates a service principal account for the application in Azure AD, and assigns the Contributor role for the account in your current subscription.
Creates an Automation certificate asset named AzureRunAsCertificate in the specified Automation account.
Creates an Automation connection asset named AzureRunAsConnection in the specified Automation account.
Please note the following requirements from the referenced link:
You must have an Azure Automation Account with an Azure Run As account already prepared. If you don’t have this yet, learn how to create one when you go to Create a new Automation account in the Azure portal.
The Azure PowerShell module must be installed. If you don’t have this yet, please go to the Install the Azure PowerShell module page for more information.
Note: You can configure your Runbook to use managed identities as well and it has added benefits as compared to using Run As accounts. You can get started with this tutorial to use managed identity.

Azure Powershell - AzureAdUser V AzAdUser

I have the free developer E5 subscription and have setup a tenancy, created users etc. I have tried creating a second directory that I am planning to use to test the Azure AD Connect tool on a local server. I can switch between the tenants on the Azure Portal with the "Switch tenant" button however can't seem to figure it out with the Powershell cmdlets.
Connect-AzureAD
Set-AzContext -TenantId "My new tenant/directory"
Following these two commands is where the confusion starts. The first commands lists the users from the first directory and the second command shows the users from the directory I have switched too.
Get-AzureAdUser (Shows the first directory, not the one switched too)
Get-AzAdUser (Shows the users of the directory switched too)
Not sure if there is something I am missing here?
Thats because those are commands from 2 different modules:
First one are from AzureAD which is a module designed for tasks within AzureAD
Ths second one are from Az With is designed to handle most, if not all of Azure's resources. The AD functionality is mostly for the module to handle lookups of azure ad objects when checking rbac and assigning access, and not really created to manage AzureAD in any meaningful way (even tho you can do some tasks).
For your task you can use the az module easliy if you just want to look up the users, but if you need to actually administer azure ad i suggest you go for azuread.
To connect to a specified tenant with azuread use connect-azuread -tenantId 'tenant id'. I also think it support that you use domain name aswell

How to determine which API Permissions are necessary to run a particular Azure PowerShell command?

I have a service principal that I use for automation. It has the Directory.Read.All permission in Microsoft Graph for our Azure Active Directory.
It cannot run the Set-AzSqlServerActiveDirectoryAdministrator command. The error I get is:
Cannot find the Azure Active Directory object 'My-AD-Group'.
Please make sure that the user or group you are authorizing is
registered in the current subscription's Azure Active directory.
If I run this same command as myself, it runs just fine.
Clearly my Service Principal needs more than the Directory.Read.All permission. Yet I cannot find any documentation that lists exactly what API Permissions my Service Principal would need to successfully run this command.
Does anyone know how I can discover exactly what API permissions would be required to run a particular Azure PowerShell command that involves accessing Azure Active Directory?
As an aside, I'm not tied to PowerShell. I cannot get this command to work with the az cli either. I'm open to methods using az that would get me this answer.
You need to give the Directory.Read.All(Application permission) of Azure AD Graph API not the Microsoft Graph API. Also make sure the service principal has the permission of the sql server(e.g. the service principal is the Owner of the subscription or the sql server), then it will work fine.
If you want to add the service principal as a role of the subscription or sql server, navigate to the subscription or the sql server in the portal -> Access control (IAM) -> Add -> Add role assignment -> search your service principal with name and add it as a role(e.g. Owner) -> Save, more details here.
Set-AzSqlServerActiveDirectoryAdministrator -ResourceGroupName "<ResourceGroupName>" -ServerName "<ServerName>" -DisplayName "group1" -ObjectId "64d1b8xxxxx4ffbd"
Does anyone know how I can discover exactly what API permissions would be required to run a particular Azure PowerShell command that involves accessing Azure Active Directory?
The Azure PowerShell essentially calls the different APIs, to get the permissions of the APIs, you could catch the request via Fiddler, then look into the official API doc for the permissions.

How do you configure Azure Function authentication by code?

I want to configure the authentication for my Azure function via code, be it powershell, ARM template or an API? is this possible?
i'm under the impression that an Azure Function is nothing more then an App Service so i would assume it resolve around there.
https://learn.microsoft.com/en-us/powershell/module/az.websites/?view=azps-2.0.0#app_service - there doesn't seem to be anything in the powershell.
https://resources.azure.com/ doesn't seem to give much information.
Here is some documentation on how to use managed identities for App Service and Azure Functions: https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity
You could create an PowerShell function app with MSI (Managed Service Identity) enable in a consumption plan. Here is some documentation (https://azure.microsoft.com/en-us/resources/templates/101-functions-managed-identity/) on how to do that.
Once the function app is created, you can grant it access to a given resource https://learn.microsoft.com/en-us/powershell/module/az.resources/new-azroleassignment?view=azps-2.0.0#examples
Lastly, the PowerShell function app comes with a profile.ps1 which contains code to authenticate against Azure via MSI out the box.
# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
if ($env:MSI_SECRET -and (Get-Module -ListAvailable Az.Accounts)) {
Connect-AzAccount -Identity
}
Please give it a try and let us know if you run into any issues.
Azure Functions Authentication are still pending. Currently AFAIK there is not a way to add authentication via code except with the Function Host Keys
You can track the issue here in Github
Using terraform is a really good way of configuring these, a good example is below. Also az CLI 'az webapp auth' seems to have really good support now. PowerShell still seems to be lagging behind.
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/function_app

Resources