Search code examples
azurejenkinsazure-storageazure-cli

Best practices for using Azure CLI in a Azure VM via Jenkins


I am pretty new with Azure. I have a Jenkins Cluster. Jobs are launched in slaves. Slaves are Azure VM (Ubuntu).

I need to run some Azure CLI commands for deploying files to an Azure Storage Blob.

I think I need to have an identity (user?) allowed to use Azure CLI inside the VM.

Maybe can I create a specific user for Jenkins only? Is a Managed Identity could use Azure CLI as well?

I wonder what is the best way accomplishing this. Thanks.


Solution

  • I have tested in my environment.

    Please create a Service Principal either using the Portal or Azure CLI.

    To create the service principal using CLI, please use below command :

    az ad sp create-for-rbac --name ServicePrincipalName
    

    Please refer for more details : https://learn.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli

    To create service principal using Portal,

    Go to Azure Active Directory --> App Registrations --> New Registration --> Complete the form --> Register

    enter image description here

    Go to your Storage Account --> Select Access Control (IAM)--> Add Role Assignment --> Under Role, select Storage Account Contributor --> Under Select, search for your Service Principal --> Click on Save

    enter image description here

    Now, the service principal will have Storage Account contributor access. You can deploy the files to Azure Storage using CLI.

    Go to Azure Active Directory --> App Registrations --> Search for your Service Principal and click on it.

    Please note the Application ID, Tenant ID.

    Go to Clients & secrets --> Click on New Client Secret --> Fill the form and click Ok.

    Note the Client Secret.

    Inside the VM, please use below command to login to Azure using your Service Principal

    az login --service-principal -u <app-id> -p <client-secret> --tenant <tenant-id>
    

    Now you can deploy the files to the Azure Storage account from the VM using CLI.

    To upload a file to your Storage Account, please use below CLI command :

    az storage blob upload --account-name StorageAccountName --container-name ContainerName --name fileName --file sourceFileName