You can use a GitLab CI Job JWT token to login to Azure from within a CI/CD pipeline without needing to store secrets in a GitLab project. In order to do this, you will also need to configure OpenID Connect (OIDC) for ID federation between GitLab and an Azure service principal. This is recommended by Microsoft for authenticating to Azure from CI/CD services, among other use cases.
Note: Using OIDC as described below will only work if you are using gitlab.com or a publicly reachable GitLab instance. This is because Azure needs to connect to the token issuer for the keys to validate the token. If you are self-hosting GitLab and your instance is not publicly accessible, you can choose a different credential type for step 2.
1. Create a registered app
First, you will need to register an Application in Azure. You can do this by following these instructions to register an application and create a service principal.
After doing this, make note of the values for Application (client) ID and Directory (tenant) ID (found in the application Overview pane). These values will be needed for step 3.
2. Add the federated credentials
Once your app is registered, you can add federated credentials to the application's service principal. In the Azure portal, go to registered apps -> your application. In the sidebar, select Certificates & secrets. Under the Federated credentials tab, click the "Add credential" button
Use the following parameters for the credential configuration:
Federated credential sceanrio: Other issuer
Issuer: your gitlab URL e.g. https://gitlab.example.com
Subject Identifier: The value of the sub
claim to match. For example, to allow jobs on the main
branch of the contoso/myproject
project to use this service principal, use project_path:contoso/myproject:ref_type:branch:ref:main
Name: Any descriptive name for the federated credental (e.g. contoso-myproject-main
)
Description: Optional, a description for the federated credential.
Audience: your GitLab URL e.g. https://gitlab.example.com
3. Authenticate to Azure in your job
After the federated credentials are created, you can leverage the CI_JOB_JWT_V2
token in your job to authenticate with Azure. In this example, we'll use the Azure CLI (az login
).
azure-cli:
image: mcr.microsoft.com/azure-cli
variables:
AZURE_CLIENT_ID: "YOUR Application Client ID"
AZURE_TENANT_ID: "YOUR TENANT ID"
script:
- az login --tenant $AZURE_TENANT_ID --service-principal -u $AZURE_CLIENT_ID --federated-token $CI_JOB_JWT_V2
# now you are logged into Azure and can take other actions using the CLI
# - az resource list # example
CI_JOB_JWT_V2
: Predefined variable
AZURE_CLIENT_ID
: The Application (Client) ID of the registered application.
AZURE_TENANT_ID
: The ID of the Azure Tenant to login to (can be found in the application overview)
Also, don't forget to grant your registered app appropriate permissions for Azure container registry