Proper way to update Docker image in Kubernetes manifest file using Azure Pipelines

Viewed 382

I have successfully built and pushed a docker image to Docker Hub using the Docker task using Azure Pipelines.

Now I would like to take that Docker image and deploy it to my Kubernetes cluster in AKS.

I need to update the image by using kubectl apply. I need to use kubectl apply specifically and not replace, edit, or patch.

How can I achieve that while also updating spec.containers.image in my deploy.yml file?

I basically want to take this variable tag: '$(Build.BuildId)', replace spec.containers.image in deploy.yml and then run kubectl apply -f deploy.yml.

Here's my deploy.yml file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myprojectname
  namespace: my-namespace
  labels:
    app: myprojectname
spec:
  replicas: 1
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      web: myprojectname
  template:
    metadata:
      labels:
        app: myprojectname
        web: myprojectname
        type: webapp
    spec:
      containers:
        - name: myprojectname
          image: mydockerhubaccount/myprojectname:25
          resources:
            requests:
              cpu: 20m
              memory: 100Mi
            limits:
              cpu: 500m
              memory: 130Mi
          ports:
            - containerPort: 80

Here's my azure-pipelines.yml file:

# Docker
# Build and push an image to Azure Container Registry
# https://docs.microsoft.com/azure/devops/pipelines/languages/docker

trigger:
- master

resources:
- repo: self

variables:
  # Container registry service connection established during pipeline creation
  dockerRegistryServiceConnection: 'Docker Hub'
  imageRepository: 'mydockerhubaccount/myprojectname'
  dockerfilePath: '$(Build.SourcesDirectory)/my-project-name/Dockerfile'
  tag: '$(Build.BuildId)'

  # Agent VM image name
  vmImageName: 'ubuntu-latest'

stages:
- stage: Build
  displayName: Build and push stage
  jobs:
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)
    steps:
    - task: Docker@2
      displayName: Build and push an image to container registry
      inputs:
        command: buildAndPush
        repository: $(imageRepository)
        dockerfile: $(dockerfilePath)
        containerRegistry: $(dockerRegistryServiceConnection)
        tags: |
          $(tag)
        buildContext: '$(Build.SourcesDirectory)'
0 Answers
Related