I’m creating solutions on GitHub for Azure, aiming to deploy them easily via GitHub Actions. To achieve this, you need to authorize GitHub securely, and writing credentials directly in the pipeline is not recommended.
A better approach is to use a Service Principal and store the credentials as a GitHub Secret.
If you prefer using Managed Identities, this is also possible but requires your own build agents. The standard public build agents of GitHub do not support Managed Identities.
Step 1 – Create a Service Principal with Azure CLI
There are several ways to create a Service Principal, but my preferred method is using the Azure CLI tool `az`.
$subscriptionId='<yoursubscriptionid>'
$appName='<yourAppName>'
$resourceGroup='<yourResourceGroupName>'
az login
az account set -s $subscriptionId
az ad app create --display-name $appName
az ad sp create-for-rbac --name $appName `
--role contributor `
--scopes /subscriptions/$subscriptionId//resourceGroups/$resourceGroup
Save the result securely, you never get the `clientSecret` value again.
{
"clientId": "******",
"clientSecret": "******",
"subscriptionId": "******",
"tenantId": "******",
...
}
You need exactly these four values; you can remove all others.
Next, add the contributor role to this Service Principal. This allows the principal to create resources in an Azure Resource Group.
az role assignment create --role contributor `
--subscription $subscriptionId `
--assignee-object-id $clientId `
--assignee-principal-type ServicePrincipal `
--scope /subscriptions/$subscriptionId/resourceGroups/$resourceGroup
Step 2 – Store Azure Credentials in GitHub Secrets
Take the JSON with the four values and go to GitHub –> Settings –> Secrets and Variables –> Actions –> Repository Settings. Add a new secret named `AZURE_CREDENTIALS`.
You won’t be able to see these values again, but you can completely overwrite them with new values if needed.
Step 3 – Use the Settings in GitHub Actions
Use this secret to login within your GitHub Action.
```yaml
- name: Azure Login
uses: Azure/login@v2.0.0
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}
```
More Information
The GitHub Action for Login into Azure: https://github.com/Azure/login
Dokumentation: https://learn.microsoft.com/en-us/azure/developer/github/connect-from-azure
Azure CLI Script: https://learn.microsoft.com/en-us/cli/azure/azure-cli-sp-tutorial-1?tabs=bash