Azure CLI (Command-Line Interface) is a powerful tool for managing Azure services. Although people commonly use interactive login methods with Azure CLI, scenarios like continuous integration and deployment in DevOps pipelines require automation or non-interactive processes. It is where Azure App Registrations and Certificates come into play, providing a secure and automated way to connect to Azure.

NOTE: The assumption is that you have already installed Azure CLI. If not, review the documentation here: https://learn.microsoft.com/en-us/cli/azure/install-azure-cli

The Role of App Registration and Certificates

An App Registration in Azure Active Directory (Azure AD) represents the identity of the application or automated tool that needs to interact with Azure resources. It is the foundation for enabling authentication and defining permissions for automated processes.

Certificates, on the other hand, are used for secure authentication. Combined with Azure App Registration, they provide a robust method for script-based login to Azure CLI without the need for interactive credential inputs. This method enhances security by avoiding storing sensitive credentials in scripts or automation servers.

Step-by-Step Guide to Using Azure CLI with App Registration and Certificate

The first step involves setting up an App Registration in Microsoft Entra ID (Azure Active Directory). It acts as the identity for your automated process or application.

  • Access Azure Portal: Log in to the Azure Portal and navigate to Microsoft Entra ID.
  • Register a New Application:
    • Go to the App Registrations section and select New Registration.
    • Provide a Name for your application.
    • Select the Supported Account Types (single or multi-tenant, based on your requirement).
    • Specify the Redirect URI (optional for CLI purposes).
    • Click Register to create the App Registration.

Note the Application (Client) ID: Azure will assign an Application ID (or Client ID) to your App Registration after creation. Record this ID, as you will need it later.

The next step is to retrieve and upload a certificate. Certificates are crucial for secure authentication. You can generate a self-signed certificate or use an existing one. You can create a certificate using tools like OpenSSL or PowerShell. Here’s how you can do it in PowerShell:

$cert = New-SelfSignedCertificate `
      -Subject "CN=AzureCLI" `
      -CertStoreLocation "cert:\CurrentUser\My" `
      -KeyExportPolicy Exportable `
      -KeySpec Signature

The above command creates a new self-signed certificate and stores it in the personal certificate store of the current user. Now, you need to export the Certificate in PEM format. You must export the Certificate and the Private Key separately in the PEM format. PowerShell doesn’t natively support exporting directly to PEM, but you can use the .NET classes to achieve this.

$certPath = "path\to\Cert.cer"
$pemCertPath = "path\to\Cert.pem"

Export-Certificate -Cert $cert -FilePath $certPath

$certContent = [System.IO.File]::ReadAllBytes($certPath)
$pemCertContent = [System.Convert]::ToBase64String($certContent, [System.Base64FormattingOptions]::InsertLineBreaks)
$pemCertOutput = "-----BEGIN CERTIFICATE-----`n$pemCertContent`n-----END CERTIFICATE-----"
[System.IO.File]::WriteAllText($pemCertPath, $pemCertOutput)

You’ll then need OpenSSL to convert the private key to PEM format. First, export the private key as a PFX file, then use OpenSSL to convert it to PEM.

$pfxPath = "path\to\yourKey.pfx"
$pemKeyPath = "path\to\yourKey.pem"
$pfxPassword = "Password"

Export-PfxCertificate `
      -Cert $cert `
      -FilePath $pfxPath `
      -Password (ConvertTo-SecureString 
			-String $pfxPassword -Force -AsPlainText)

openssl pkcs12 -in $pfxPath -out $pemKeyPath -nodes -passin pass:$pfxPassword

The folder should now contain these four files:

Now, you need to upload the Certificate to the App Registration. You do this by navigating the Azure Portal and entering the App Registrations section within Microsoft Entra ID. Once there, select the App Registration you created and click Certificates & Secrets, then under Certificates, click on Upload Certificate and upload the CER file.

Your App Registration needs the necessary permissions (API permissions and role assignments) to perform actions in Azure (if that is what is required). In the App Registration, go to API Permissions and add the necessary permissions (e.g., Microsoft Graph, Azure Service Management). More importantly, you need to assign the correct permissions to the App Registration within the Azure Portal so it can access the subscriptions.

If you don’t assign access, you will get a “No subscriptions found for {Tenant ID}.” message after you connect.

With the App Registration and Certificate in place, the next step is to configure Azure CLI to authenticate using these components.

To log in using the Service Principal, you need to use your command-line interface and execute the following command to log in using the service principal created earlier. 

Replace <appId><tenantId>, and <certificatePath> with your Application IDTenant ID, and the path to your PFX certificate file, respectively.

az login \
      --service-principal \
      --username <appId> \
      --tenant <tenantId> \
      --password <certificatePath>

In the above code, the –username is your Application (client) ID–tenant is your Azure AD tenant ID, and –password is the path to the PFX file containing your Certificate and its private key.

After running the login command, you can verify the successful authentication by executing:

az account show

The above command displays the currently active subscription and tenant, confirming that the CLI is now operating under the context of the service principal.

Once you have configured Azure CLI for non-interactive authentication, you can easily automate various Azure tasks without manual intervention. With Azure CLI commands, you can write scripts in languages like Bash and PowerShell for resource management, security checks, and service deployment tasks. You can then integrate these scripts into your CI/CD pipelines to automate configuration, deployment, and security assurance tasks.

Practical Azure CLI Queries for IT Administrators

In managing Azure environments, IT administrators frequently need to execute various queries to monitor, manage, and audit resources. Below are four simple yet practical Azure CLI queries commonly used in day-to-day administration tasks:

Listing All Virtual Machines in a Subscription: This command provides a tabulated list of Virtual Machine names, resource groups, and current power states (e.g., running, stopped). 

az vm list \
      --show-details \
      --query "[].{Name:name, ResourceGroup:resourceGroup, Status:powerState}" \
      -o table

Checking the Status of All Network Security Groups (NSGs): This output helps identify existing NSGs, allowing for a more detailed examination of their specific rules.

az network nsg list \
      --query "[].{Name:name, ResourceGroup:resourceGroup}" \
      -o table

Viewing Storage Account Details: The following command helps administrators quickly understand the types of storage accounts in use and their access tiers, which is crucial for cost management and performance considerations.

az storage account list \
      --query "[].{Name:name, Type:sku.name, AccessTier:accessTier}" \
     -o table

Auditing Role Assignments: This query provides a comprehensive view of role assignments, helping administrators monitor access rights and ensure adherence to the principle of least privilege.

az role assignment list \
      --query "[].{Principal:principalName, Role:roleDefinitionName, Scope:scope}" \
      -o table

Conclusion

These represent a handful of instructions you can carry out once linked to your Azure Tenant. The Azure CLI tool is fundamental for IT administrators, offering a swift and effective way to manage Azure assets. It streamlines regular checks of digital machines, scrutinizes network security arrangements, oversees storage solutions, and audits access controls with its intuitive syntax and powerful abilities. The concise command framework of Azure CLI saves time and enhances the overall efficiency and security of Azure environments. As cloud technologies progress, Azure CLI stays a crucial part of the kit of every Azure professional, as it enables them to navigate and manage their cloud assets expertly.

In future posts, I will expand on the types of commands you can run using Azure CLI, specifically when trying to review an Azure Tenant.