Authenticate to Azure Automatically with the Azure CLI

We host various scripts and Ansible playbooks on a Linux box. These scripts/playbooks do things on Azure resources. Currently, an admin has to login to the server, authenticate to Azure with the AZ CLI, and then run the scripts and playbooks. We're all busy these days, so why not automate some of these tasks? Seems simple enough... The only problem is how can we have the server automatically authenticate to Azure without any user intervention? Surprisingly, there is a fairly simple (though little known) answer: use an Azure AD service principal.

We'll assign the server an Azure AD Service Principal, which it can then use to authenticate to Azure.

To do this, first login to the Azure CLI by typing in "az login". You can also create a service principal from PowerShell, the Azure Portal, or the Graph API. In this example we will be using the Azure CLI.

If you have multiple subscriptions, you can select your subscription context with this cmd (replace <subscriptionId> with your subscription ID):

az account set -s <subscriptionId>

If you're not sure what your subscription ID is, you can show all subscriptions by typing in: "az account list -o table"

Now, let's create our service principal. Type in "az ad sp create-for-rbac -n "my-servicePrincipal" --create-cert:

Note the location of the .pem file. You will need this, the tenant ID, and the value of the "name" attribute (URI) when authenticating.

Logout of your account using "az logout"

To login using the certificate (.pem file), type in the following:

az login --service-principal --username "<http://my-servicePrincipal>" --password /home/<myUsername>/myPemFile.pem --tenant <myTenantId>

You can even export these values to environment variables for use later, use them in a script, etc. By default, this new service principal will have contributor role access to the subscription. If you want to change this, use the "-role" argument when creating the principal.

comments powered by Disqus