Search code examples
azurejenkinsazure-batch

use Azure Batch as Jenkins' node


I have a Jenkins server that is running well with other machines as node. I have also a Azure Batch account and a working pool. Is there a way to connect both so that Jenkins tasks are sent to the Azure Batch pool?

So far I have only found this https://github.com/Azure/batch-jenkins that is a post-build plugin to execute tests in parallel, that's not what I am looking for. I just need to send a command line to Azure.

Thank you


Solution

  • As your requirement is to send a command line to Azure so I would suggest you to have a simple Jenkins job (either freestyle job or pipeline job) which would accomplish the requirement.

    Pre-requisites:

    1. Have an Azure Batch account
    2. Have an Azure Batch pool
    3. Have an Azure Batch job
    4. Azure CLI installed in the Jenkins node where you would run the Jenkins job
    5. Add Azure service principal to Jenkins credential as instructed here

    Then have a Jenkins freestyle job executing commands similar to below one in shell build step after connecting to Azure CLI using Azure service principal.

    az login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET -t $AZURE_TENANT_ID
    
    az batch task create --task-id mytask$i --job-id myjob --command-line "/bin/bash -c 'xxxxxxxxxxxxxxxxxxxxx; sleep 90s'"
    

    Or else have a Jenkins pipeline job something like shown below.

    #!groovy
    node {
        try {
            xxxxxxxxxxxxxxxxxxxxx
            xxxxxxxxxxxxxxxxxxxxx
        }
        catch (MissingPropertyException e) {
            xxxxxxxxxxxxxxxxxxxxx
            xxxxxxxxxxxxxxxxxxxxx
        }
        stage('test'){
            withCredentials([azureServicePrincipal('JENKINSSERVICEPRINCIPALCREDENTIALID')]) {
                def sampleoutputone = sh (returnStdout: true, script: '''az login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET -t $AZURE_TENANT_ID > /dev/null
                az account set -s $AZURE_SUBSCRIPTION_ID > /dev/null
                sampleoutputtwo=$(az batch task create --task-id mytask --job-id myjob --command-line "/bin/bash -c 'xxxxxxxxxxxxxxxxxxxxx; sleep 90s'")
                xxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxx
            }
        }
    }
    

    P.S. Note that the code provided in this answer is just a sample one which you may have to tweak a bit to work as per your needs.

    Hope this helps!! Cheers!!