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:
- Go to Azure DevOps:
- Navigate to your Azure DevOps project.
- Project Settings:
- In the lower-left corner, click on Project settings.
- 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.
- Find the correct service connection:
- The
azureSubscriptionvalue should match the name of the service connection listed here. For example, it might be something likeMyAzureServiceConnection, or in your case, the name of the subscription you’re authorized to use.
- The
- 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.
- 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-credentialswrites a kubeconfig for the cluster to the agent, so thekubectlcommands 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 tokubectl apply. Azure DevOps replaces$(namespace)and$(imageName)with the variable values before bash runs the script. kubectl exposecreates aLoadBalancerService. 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 andkubectlinstalled. Runningaz aks install-cliinstallskubectlandkubelogin. Microsoft-hostedubuntu-latestagents already include both tools. - If the cluster uses Microsoft Entra ID integration,
kubeloginmust 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.
- In Project settings > Service connections, select New service connection > Azure Resource Manager.
- Choose the automatic option with workload identity federation. Scope it to the resource group that contains the cluster, for example
aks. - Give it a clear name. That exact name goes into
azureSubscriptionin the YAML. - 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 setup | Minimum 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 RBAC | Cluster User Role, plus a Kubernetes RoleBinding for the identity in the target namespace |
| Entra ID integration with Azure RBAC for Kubernetes | Cluster 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 pipefailstops 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. ChangeimageNameand the next run rolls out the new version. kubectl rollout statuskeeps 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
defaultis created on purpose.defaultalways 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
| Error | Cause | Fix |
|---|---|---|
Service connection aks could not be found or is not authorized | The name in azureSubscription doesn't match the connection, or the pipeline hasn't been granted access to it | Copy 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 granted | The organization has no Microsoft-hosted agent capacity | Request the free grant, buy parallel jobs, or use a self-hosted pool such as DevOpsSchool |
az: command not found or kubectl: command not found | A self-hosted agent is missing the tools | Install the Azure CLI, then run az aks install-cli. Restart the agent so its PATH updates |
AuthorizationFailed on listClusterUserCredential | The pipeline identity has no role on the cluster | Assign Azure Kubernetes Service Cluster User Role or Contributor on the cluster or resource group |
kubelogin is not installed or an interactive device-login prompt hangs | The cluster uses Entra ID authentication | Install kubelogin and run kubelogin convert-kubeconfig -l azurecli after get-credentials |
services "nginx-service" already exists | kubectl expose was run a second time | Declare the Service in a manifest and use kubectl apply, as in the corrected pipeline |
| Forbidden: cannot create deployments in namespace | The identity can sign in to the cluster but has no Kubernetes RBAC rights | Add 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
deploymentjob 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 statusreports 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
- More Azure tutorials
- More Kubernetes tutorials
- Troubleshooting Guide to Resolving 500 Errors in Kubernetes Production Environments
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals