DEV Community

Cover image for How to deploy to Azure with GitLab (authentication in Azure and YAML pipeline example)
Evgeny Rudinsky
Evgeny Rudinsky

Posted on • Edited on

How to deploy to Azure with GitLab (authentication in Azure and YAML pipeline example)

In this short post you'll find how to prepare your GitLab to deploy to Azure.

1 - Service Principal

Generate Service Principal (aka App Registration) using azure CLI (either builtin shell or local terminal, you must be logged in with Owner role credentials since we need to assign role to the scope):



az ad sp create-for-rbac --name GitLabServicePrincipalName --role Owner --scopes /

{
  "appId": "<REDACTED>",
  "displayName": "GitLabServicePrincipalName",
  "password": "<REDACTED>",
  "tenant": "<REDACTED>"
}



Enter fullscreen mode Exit fullscreen mode

Feel free to change scopes and role (i.e. custom role or subscription scope instead). Learn more how to generate SPN here.

2 - Store credentials in GitLab

Safe appId, password, tenant and subscription ID in GitLab => Settings => CI/CD => Variables (make sure to enable checkbox Mask variable for each secret so the values won't end up in the logs of the job).

3 - Configure YAML

Example of .gitlab-ci.yml:



... [REDACTED] ...

deploy-job:
image: mcr.microsoft.com/azure-cli
variables:
appId: $appId
password: $password
tenant: $tenant
subId: $subId
stage: deploy
script:
- az login --service-principal -u $appId -p $password -t $tenant
- az account set -s $subId
- az group list

... [REDACTED] ...

Enter fullscreen mode Exit fullscreen mode




Resources and notes

  • Microsoft offers docker image with latest and greatest Azure CLI;
  • Variables are not available automatically after adding them in GUI, we have to assign them to environment variables, that's why we have variables block in the YAML.
  • az account set -s $subId is used to make sure that the proper target subscription is set for our operations (important in case of multiple subscriptions within tenant).

Conclusion

Feel free to explore this public repo to see the entire example.

Let me know what you think. If you liked my content, follow me on twitter at @evgenyrudinsky

Until next post! 👋

Top comments (0)