Share the love

Here is an example of a YAML pipeline that can be used to build, push and deploy an application to AKS using Azure Container Registry (ACR) and Azure Kubernetes Service (AKS):

# File: azure-pipelines.yml

# This pipeline uses the classic editor

# Define variables
variables:
  # Container Registry
  containerRegistry: 'mycontainerregistry.azurecr.io'
  # Image name
  imageName: 'myappimage'
  # AKS cluster name
  aksCluster: 'myakscluster'
  # AKS resource group
  aksResourceGroup: 'myaksresourcegroup'
  # AKS namespace
  aksNamespace: 'myaksnamespace'

# Define pipeline stages
stages:
- stage: Build
  jobs:
  - job: BuildApplication
    steps:
    - script: |
        # Build application
        dotnet build
      displayName: 'Build application'
    - script: |
        # Build Docker image
        docker build -t $(containerRegistry)/$(imageName):$(Build.BuildId) .
      displayName: 'Build Docker image'
    - script: |
        # Push image to ACR
        docker push $(containerRegistry)/$(imageName):$(Build.BuildId)
      displayName: 'Push image to ACR'
- stage: Deploy
  jobs:
  - deployment: DeployToAKS
    pool:
      vmImage: 'ubuntu-latest'
    environment: 'AKS'
    strategy:
      runOnce:
        deploy:
          steps:
          - script: |
              # Login to ACR
              az acr login --name $(containerRegistry)
            displayName: 'Login to ACR'
          - script: |
              # Set the latest version of the image in ACR as the image to deploy
              IMAGE_TAG=$(containerRegistry)/$(imageName):$(Build.BuildId)
              # Deploy image to AKS
              kubectl set image deployment/$(imageName) $(imageName)=${IMAGE_TAG} -n $(aksNamespace)
            displayName: 'Deploy image to AKS'

The pipeline will have the following steps:

  1. Build: In this step, the application will be built using the appropriate command.
  2. Docker Build: In this step, the Docker image will be built using the built application. The docker build command will be used to build the image, and the -t flag will be used to specify the image name and tag. The $(Build.BuildNumber) variable will be used to set the version of the image to the build version of the pipeline.
  3. Push to ACR: In this step, the built Docker image will be pushed to the Azure Container Registry (ACR) using the docker push command. The image name and tag used in this step will be the same as in the previous step.
  4. Deploy to AKS: In this step, the latest version of the image from ACR will be deployed to AKS using the kubectl command. The kubectl set image command will be used to update the deployment with the latest image.

It is important to note that this pipeline assumes that the ACR and AKS resources have already been set up and that the pipeline has the necessary permissions to access these resources.