MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Azure Pipeline to Deploy into AKS

This page shows how an Azure DevOps YAML pipeline deploys NGINX to an Azure Kubernetes Service (AKS) cluster. It uses the AzureCLI@2 task, an Azure Resource Manager service connection and kubectl. Below the original example you will find a corrected pipeline that can run more than once, the permissions the service connection needs, a KubernetesManifest@1 alternative, and fixes for the errors that come up most often.

The azureSubscription field in the Azure DevOps pipeline YAML refers to the name or ID of the Azure service connection that you set up in Azure DevOps to authenticate and authorize the pipeline to interact with your Azure resources (e.g., your AKS cluster).

In Azure DevOps, this service connection represents the credentials (usually based on a Service Principal) that the pipeline will use to perform tasks such as deploying to AKS, accessing other Azure resources, etc.

Steps to find or create the azureSubscription value:

  1. Go to Azure DevOps:
    • Navigate to your Azure DevOps project.
  2. Project Settings:
    • In the lower-left corner, click on Project settings.
  3. Service connections:
    • Under Pipelines, click on Service connections.
    • You should see a list of service connections if any are already set up. These represent the available Azure subscriptions that your pipeline can use.
  4. Find the correct service connection:
    • The azureSubscription value should match the name of the service connection listed here. For example, it might be something like MyAzureServiceConnection, or in your case, the name of the subscription you’re authorized to use.
  5. Create a new service connection (if necessary):
    • If you don’t have a service connection set up, click New service connection.
    • Choose Azure Resource Manager and follow the steps to create a new connection using either:
      • Service Principal (automatic) (recommended) โ€“ this will automatically set up a Service Principal and permissions for you.
      • Service Principal (manual) โ€“ this allows you to manually enter details such as Subscription ID, Service Principal ID, and Secret if you’ve set up credentials manually in Azure.
    • After setting it up, you can use the name of this service connection in your pipeline YAML.
  6. Use in the pipeline:

How the example pipeline works

The pipeline in the example above runs one stage with one job. Its main work happens in a single AzureCLI@2 step. That task signs in to Azure as the identity behind the service connection named in azureSubscription. It then runs your script with that Azure CLI session already open.

  • az aks get-credentials writes a kubeconfig for the cluster to the agent, so the kubectl commands that follow talk to AKS.
  • kubectl create namespace ... --dry-run=client -o yaml | kubectl apply -f - creates the namespace only if it does not exist yet. This is a common pattern that is safe to run repeatedly.
  • The heredoc (<<EOF ... EOF) sends a Deployment manifest straight to kubectl apply. Azure DevOps replaces $(namespace) and $(imageName) with the variable values before bash runs the script.
  • kubectl expose creates a LoadBalancer Service. AKS gives the Service a public IP through the Azure load balancer.

Note: If you reference a variable that is not defined, Azure DevOps leaves $(name) unchanged. Bash then reads it as command substitution and fails with name: command not found. Check variable names carefully.

Prerequisites

  • An existing AKS cluster, plus its resource group name and cluster name.
  • An Azure Resource Manager service connection in the Azure DevOps project. Its name is the value you put in azureSubscription.
  • An agent that can run the job. The example uses a self-hosted pool called DevOpsSchool. That machine must have the Azure CLI and kubectl installed. Running az aks install-cli installs kubectl and kubelogin. Microsoft-hosted ubuntu-latest agents already include both tools.
  • If the cluster uses Microsoft Entra ID integration, kubelogin must also be on the agent.

Creating the service connection and granting access

The steps above describe creating a connection with a service principal and a secret. In current versions of Azure DevOps, the recommended credential type is workload identity federation. It uses short-lived tokens, so there is no secret to store or rotate. If you have a choice, create a new Azure Resource Manager connection with workload identity federation. Azure DevOps can also convert many existing secret-based connections.

  1. In Project settings > Service connections, select New service connection > Azure Resource Manager.
  2. Choose the automatic option with workload identity federation. Scope it to the resource group that contains the cluster, for example aks.
  3. Give it a clear name. That exact name goes into azureSubscription in the YAML.
  4. On the first pipeline run, Azure DevOps may ask you to Permit the pipeline to use the connection. You can also grant access to all pipelines on the connection's security page.

The connection's identity needs Azure RBAC rights on the cluster. If you scope an automatic connection to a resource group, it usually gets Contributor on that group, which is enough for az aks get-credentials. If you create the identity yourself, assign at least the roles below.

Cluster setupMinimum role for the pipeline identity
Local accounts (no Entra ID integration)Azure Kubernetes Service Cluster User Role, so the identity can download credentials
Entra ID integration with Kubernetes RBACCluster User Role, plus a Kubernetes RoleBinding for the identity in the target namespace
Entra ID integration with Azure RBAC for KubernetesCluster User Role, plus Azure Kubernetes Service RBAC Writer (or higher) on the cluster or namespace

Corrected pipeline that can run repeatedly

The original works on its first run but has a few problems. On the second run, kubectl expose fails because the Service already exists. The script also has no set -e, so an earlier failure can be hidden. The image is the floating latest tag. The version below declares both the Deployment and the Service and sends them to kubectl apply. Because apply is declarative, every run gives the same result. The pipeline then waits for the rollout to finish.

trigger:
  branches:
    include:
      - main
      - master

pool:
  vmImage: 'ubuntu-latest'      # or, for a self-hosted pool:  name: DevOpsSchool

variables:
  imageName: 'nginx:1.27'       # pin a version instead of :latest
  aksResourceGroup: 'aks'
  aksClusterName: 'CSCluster'
  namespace: 'web'

stages:
- stage: Deploy
  displayName: Deploy to AKS
  jobs:
  - job: DeployToAKS
    displayName: Deploy to AKS
    steps:
    - task: AzureCLI@2
      displayName: Apply NGINX to AKS
      inputs:
        azureSubscription: 'aks'   # name of your Azure Resource Manager service connection
        scriptType: 'bash'
        scriptLocation: 'inlineScript'
        inlineScript: |
          set -euo pipefail

          az aks get-credentials --resource-group "$(aksResourceGroup)" --name "$(aksClusterName)" --overwrite-existing
          # Entra ID-integrated clusters only: reuse the pipeline's az login for kubectl
          # kubelogin convert-kubeconfig -l azurecli

          kubectl create namespace "$(namespace)" --dry-run=client -o yaml | kubectl apply -f -

          kubectl apply -f - <<EOF
          apiVersion: apps/v1
          kind: Deployment
          metadata:
            name: nginx-deployment
            namespace: $(namespace)
          spec:
            replicas: 2
            selector:
              matchLabels:
                app: nginx
            template:
              metadata:
                labels:
                  app: nginx
              spec:
                containers:
                - name: nginx
                  image: $(imageName)
                  ports:
                  - containerPort: 80
                  resources:
                    requests:
                      cpu: 50m
                      memory: 64Mi
                    limits:
                      memory: 128Mi
          ---
          apiVersion: v1
          kind: Service
          metadata:
            name: nginx-service
            namespace: $(namespace)
          spec:
            type: LoadBalancer
            selector:
              app: nginx
            ports:
            - port: 80
              targetPort: 80
          EOF

          kubectl rollout status deployment/nginx-deployment -n "$(namespace)" --timeout=180s
          kubectl get svc nginx-service -n "$(namespace)"
  • set -euo pipefail stops the script at the first command that fails, so the task fails with it. Without it, the task reports only the exit code of the last command.
  • With kubectl apply, a rerun updates the existing objects and does not fail. Change imageName and the next run rolls out the new version.
  • kubectl rollout status keeps the job running until the pods are ready. If the image can't be pulled or the pods crash, the pipeline fails instead of reporting success.
  • Every namespace except default is created on purpose. default always exists, so creating it in the original did nothing.

Note: Leave the YAML indentation of the heredoc as shown. Azure DevOps removes the shared leading spaces from the inlineScript block, so apiVersion: and the closing EOF both end up in column 0. If EOF is indented differently from the rest, bash cannot find the end of the heredoc.

Checking the deployment

The last step prints the Service. Azure can take a minute or two to assign the public IP. Until then, EXTERNAL-IP shows <pending>. You can run the same checks from your own machine after running az aks get-credentials:

kubectl get deploy,pods,svc -n web

# Example output (trimmed)
# NAME                               READY   UP-TO-DATE   AVAILABLE
# deployment.apps/nginx-deployment   2/2     2            2
# NAME                    TYPE           CLUSTER-IP    EXTERNAL-IP     PORT(S)
# service/nginx-service   LoadBalancer   10.0.123.45   20.x.x.x        80:3xxxx/TCP

curl -I http://<EXTERNAL-IP>Code language: PHP (php)

Alternative: the KubernetesManifest task

For real applications, keep the manifests in the repository and deploy them with KubernetesManifest@1. You get no shell scripting. The task can also replace image tags at deploy time and supports canary strategies. It connects through the same Azure Resource Manager service connection.

- task: KubernetesManifest@1
  displayName: Deploy manifests
  inputs:
    action: 'deploy'
    connectionType: 'azureResourceManager'
    azureSubscriptionConnection: 'aks'
    azureResourceGroup: '$(aksResourceGroup)'
    kubernetesCluster: '$(aksClusterName)'
    namespace: '$(namespace)'
    manifests: |
      k8s/deployment.yaml
      k8s/service.yaml
    containers: '$(imageName)'Code language: CSS (css)

Common errors and fixes

ErrorCauseFix
Service connection aks could not be found or is not authorizedThe name in azureSubscription doesn't match the connection, or the pipeline hasn't been granted access to itCopy the exact connection name. Then approve the permission prompt on the run, or grant pipeline access on the connection
No hosted parallelism has been purchased or grantedThe organization has no Microsoft-hosted agent capacityRequest the free grant, buy parallel jobs, or use a self-hosted pool such as DevOpsSchool
az: command not found or kubectl: command not foundA self-hosted agent is missing the toolsInstall the Azure CLI, then run az aks install-cli. Restart the agent so its PATH updates
AuthorizationFailed on listClusterUserCredentialThe pipeline identity has no role on the clusterAssign Azure Kubernetes Service Cluster User Role or Contributor on the cluster or resource group
kubelogin is not installed or an interactive device-login prompt hangsThe cluster uses Entra ID authenticationInstall kubelogin and run kubelogin convert-kubeconfig -l azurecli after get-credentials
services "nginx-service" already existskubectl expose was run a second timeDeclare the Service in a manifest and use kubectl apply, as in the corrected pipeline
Forbidden: cannot create deployments in namespaceThe identity can sign in to the cluster but has no Kubernetes RBAC rightsAdd a RoleBinding, or assign an Azure Kubernetes Service RBAC role for that namespace

If the pods are running but the application returns server errors, see the 500 errors troubleshooting guide.

Best practices

  • Use workload identity federation, and scope the service connection to the cluster's resource group, not the whole subscription.
  • Deploy through a deployment job that targets an Azure DevOps environment. This adds approvals, checks and deployment history before production.
  • Pin image tags, or better, digests. For your own images, build them in an earlier stage and push them to Azure Container Registry.
  • Keep the manifests (or a Helm chart) in Git, not inline in the pipeline, so they can be reviewed and reused.
  • Add readiness and liveness probes to the containers so rollout status reports real application health.

Frequently asked questions

What value goes in azureSubscription in an Azure DevOps pipeline?

The name of an Azure Resource Manager service connection in your project. The name of the Azure subscription itself won't work. The pipeline also needs permission to use that connection.

Do I need kubectl installed on the agent to deploy to AKS?

Microsoft-hosted Ubuntu agents already have kubectl and the Azure CLI. On a self-hosted agent you must install the Azure CLI, then run az aks install-cli to add kubectl and kubelogin.

Why does my AKS pipeline fail the second time it runs?

Imperative commands such as kubectl expose and kubectl create fail when the object already exists. Define your resources in manifests and use kubectl apply, which creates or updates them on every run.

Should I use AzureCLI@2 or KubernetesManifest@1 to deploy to AKS?

AzureCLI@2 suits quick scripts and any custom kubectl or az commands. KubernetesManifest@1 is the better fit for manifests stored in a repository, because it handles image substitution, rollout checks and canary deployments for you.

How do I deploy to an AKS cluster that uses Microsoft Entra ID authentication?

After az aks get-credentials, run kubelogin convert-kubeconfig -l azurecli so kubectl uses the pipeline's Azure CLI login. Then give the pipeline identity a Kubernetes RBAC binding, or an Azure Kubernetes Service RBAC role, on the target namespace.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Your Comprehensive Guide to Azure DevOps Engineer Expert Mastery

The landscape of software development is constantly shifting. Gone are the days when writing code and managing servers were two completely different jobs. Today, the most successful…

Read More

Complete Guide to Master in Azure DevOps

The shift from traditional software delivery to modern cloud-native systems has changed everything. I have watched the industry move from manual server setups to a world where…

Read More

What is AZURE DEVOPS?

What is Microsoft Azure? Now, lets know about Microsoft Azure, It is a cloud computing service created by Microsoft that is one of the leading cloud service…

Read More

Azure DevOps Pipelines Fundamental Tutorials

Here is an in-depth, step-by-step tutorial on Azure DevOps Pipelines that covers everything from the fundamentals to advanced concepts. This guide is designed to help you understand…

Read More

Microsoft Certified: DevOps Engineer Expert – Exam AZ-400: Designing and Implementing Microsoft DevOps Solutions

The Exam AZ-400: Designing and Implementing Microsoft DevOps Solutions is a crucial step for IT professionals aiming to become Microsoft Certified: DevOps Engineer Experts. This certification demonstrates…

Read More

Streamlining Deployment with Azure DevOps: A Guide to Deploying to a Liquid Web VPS

The combination of Azure DevOps and Liquid Web’s Virtual Private Server (VPS) can revolutionize effective software deployment. While Liquid Web’s VPS offers a customizable and scalable hosting…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x