Saturday, 12 June 2021

Deploy AKS and ACR with GitHub Actions

 There are so many ways to write infrastructure as code such as using Terraform or Bicep for Azure. Azure CLI is a fast way to deploy infrastructure with PowerShell scripting to Azure. Deploying infrastructure in Azure with utilizing pipeline which is running infrastructure as code is useful to achieve fully automated deployments. Let's try to combine Azure CLI and GitHub Actions to deploy an AKS (Azure Kubernetes Services) with Azure container registry (ACR) association to achieve deployment automation of AKS.

Since we are going to use Azure CLI for deploying the AKS cluster via GitHub Actions we need to execute a login using az loin. Using Azure CLI commands in GitHub Actions is explained in the post "Executing Azure CLI Commands with GitHub Actions". Once az login step is completed we can following Azure CLI  commands to create resource group and ACR .

az group create --name aksRgName --location aksLocation
az acr create -n aksacrName -g env.aksRgName --sku aksacrSku

Then AKS can be create with associating the ACR to AKS using the following command.

az aks create --resource-group aksRgName --name aksClusterName --node-count 
aksClusterNodeCount --kubernetes-version aksk8sversion --attach-acr aksacrName 

In above command --attach-acr ensures the association of ACR to AKS so that AKS cluster can pull images from ACR to deploy.

The full GitHub action workflow is below. You can see environment variables are defined for parameters and used in actions. Credentials for az login is obtained from a repo secret as explained in "Executing Azure CLI Commands with GitHub Actions".

name: Deploy AKS with ACR
on: [workflow_dispatch]
    runs-on: windows-latest
      aksRgName: rg-chdemo-001
      aksLocation: eastus
      aksClusterName: aks-chdemo-001
      aksClusterNodeCount: 1
      aksk8sversion: 1.22.4
      aksacrName: acrch001
      aksacrSku: Standard
      - name: Checkout
        uses: actions/checkout@v2.3.4
      - name: 'Az CLI login'
        uses: azure/login@v1
          creds: ${{ secrets.AZURE_CREDENTIALS }}

      - name: 'Run az commands'
        shell: powershell
        run: |
          az group create --name ${{ env.aksRgName }} --location ${{ env.aksLocation }}
          az acr create -n ${{ env.aksacrName }} -g ${{ env.aksRgName }} --sku ${{ env.aksacrSku }}
          az aks create --resource-group ${{ env.aksRgName }} --name ${{ env.aksClusterName }} --node-count ${{ env.aksClusterNodeCount }} --kubernetes-version ${{ env.aksk8sversion }} --attach-acr ${{ env.aksacrName }} --generate-ssh-keys

Once the pipeline is executed the AKS cluster is created.

Created AKS is assigned with ACR pull role in ACR.

No comments:

Popular Posts