Membuat pipeline CI/CD dengan Azure Pipelines dan Google Kubernetes Engine

Last reviewed 2022-11-29 UTC

Tutorial ini menunjukkan cara menggunakan Azure Pipelines, Google Kubernetes Engine (GKE), dan Container Registry Google untuk membuat pipeline continuous integration/continuous deployment (CI/CD) untuk aplikasi web ASP.NET MVC. Untuk tujuan tutorial ini, Anda dapat memilih dua contoh aplikasi:

  • Aplikasi web ASP.NET Core yang menggunakan .NET 6.0 dan berjalan di Linux
  • Aplikasi web ASP.NET MVC yang menggunakan .NET Framework 4 dan berjalan di Windows

Pipeline CI/CD menggunakan dua cluster GKE terpisah, satu untuk pengembangan dan satu untuk produksi, seperti yang ditunjukkan diagram berikut.

Diagram konseptual pipeline CI/CD yang menunjukkan cara developer dan pengguna akhir berinteraksi dengan aplikasi

Di awal pipeline, developer melakukan commit perubahan pada codebase contoh. Tindakan ini akan memicu pipeline untuk membuat rilis dan men-deploy-nya ke cluster pengembangan. Kemudian, pengelola rilis dapat mempromosikan rilis sehingga di-deploy ke cluster produksi.

Tutorial ini ditujukan bagi developer dan engineer DevOps. Tutorial ini mengasumsikan bahwa Anda memiliki pengetahuan dasar tentang Microsoft .NET, Azure Pipelines, dan GKE. Tutorial ini juga mengharuskan Anda memiliki akses administratif ke akun Azure DevOps.

Tujuan

  • Hubungkan Google Container Registry ke Azure Pipelines untuk memublikasikan image Docker.
  • Siapkan aplikasi contoh.NET untuk deployment ke GKE.
  • Lakukan autentikasi secara aman terhadap GKE tanpa harus menggunakan autentikasi lama.
  • Gunakan pengelolaan rilis Azure Pipelines untuk mengorkestrasi deployment GKE.

Di luar cakupan

Tutorial ini tidak membahas cara menghubungkan Azure Pipelines dengan cluster GKE pribadi, atau cara menghubungkan ke jaringan pribadi yang diizinkan.

Biaya

Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga.

Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Setelah menyelesaikan tugas yang dijelaskan dalam dokumen ini, Anda dapat menghindari penagihan berkelanjutan dengan menghapus resource yang Anda buat. Untuk mengetahui informasi selengkapnya, lihat Pembersihan.

Lihat halaman harga Azure DevOps untuk mengetahui biaya yang mungkin berlaku pada penggunaan Azure DevOps.

Sebelum memulai

Biasanya disarankan untuk menggunakan project terpisah untuk workload pengembangan dan produksi sehingga peran dan izin Identity and Access Management (IAM) dapat diberikan satu per satu. Demi kesederhanaan, tutorial ini menggunakan satu project untuk kedua cluster GKE, satu untuk pengembangan dan satu untuk produksi.

  1. Di konsol Google Cloud , pada halaman pemilih project, pilih atau buat project Google Cloud .

    Peran yang diperlukan untuk memilih atau membuat project

    • Pilih project: Memilih project tidak memerlukan peran IAM tertentu—Anda dapat memilih project mana pun yang telah diberi peran.
    • Membuat project: Untuk membuat project, Anda memerlukan peran Pembuat Project (roles/resourcemanager.projectCreator), yang berisi izin resourcemanager.projects.create. Pelajari cara memberikan peran.

    Buka pemilih project

  2. Verifikasi bahwa penagihan diaktifkan untuk project Google Cloud Anda.

  3. Pastikan Anda memiliki akun Azure DevOps dan memiliki akses administrator ke akun tersebut. Jika belum memiliki akun Azure DevOps, Anda dapat mendaftar di halaman beranda Azure DevOps.

Membuat project Azure DevOps

Anda menggunakan Azure DevOps untuk mengelola kode sumber, menjalankan build dan pengujian, serta mengatur deployment ke GKE. Untuk memulai, Anda membuat project di akun Azure DevOps Anda.

  1. Buka halaman beranda Azure DevOps (https://dev.azure.com/YOUR_AZURE_DEVOPS_ACCOUNT_NAME).
  2. Klik Project Baru.
  3. Masukkan nama project, seperti CloudDemo.
  4. Setel Visibilitas ke Pribadi, lalu klik Buat.
  5. Setelah Anda membuat project, di menu sebelah kiri, klik Repos.
  6. Klik Impor untuk membuat fork repositori dotnet-docs-samples dari GitHub, lalu tetapkan nilai berikut:
    • Jenis repositori: Git
    • URL Clone: https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git
  7. Klik Import.

    Setelah proses impor selesai, Anda akan melihat kode sumber repositori dotnet-docs-samples.

Menghubungkan Azure Pipelines ke Google Container Registry

Sebelum dapat menyiapkan continuous integration untuk aplikasi CloudDemo, Anda harus menghubungkan Azure Pipelines ke Container Registry. Koneksi ini memungkinkan Azure Pipelines memublikasikan image container ke Container Registry.

Menyiapkan akun layanan untuk memublikasikan gambar

Buat akun layananGoogle Cloud di project Anda:

  1. Buka konsol Google Cloud .

  2. Di konsol Google Cloud , aktifkan Cloud Shell.

    Aktifkan Cloud Shell

  3. Untuk menghemat waktu saat mengetik opsi project ID dan zona Compute Engine, tetapkan nilai konfigurasi default dengan menjalankan perintah berikut:

    gcloud config set project PROJECT_ID
    gcloud config set compute/zone us-central1-a
    

    Ganti PROJECT_ID dengan project ID project Anda.

  4. Aktifkan Container Registry API di project:

    gcloud services enable containerregistry.googleapis.com
    
  5. Buat akun layanan yang digunakan Azure Pipelines untuk memublikasikan image Docker:

    gcloud iam service-accounts create azure-pipelines-publisher \
        --display-name="Azure Pipelines Publisher"
    
  6. Berikan peran IAM Administrator Artifact Registry (roles/artifactregistry.admin) ke akun layanan agar Azure Pipelines dapat melakukan push ke Container Registry:

    AZURE_PIPELINES_PUBLISHER=azure-pipelines-publisher@$GOOGLE_CLOUD_PROJECT.iam.gserviceaccount.com
    
    gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT \
        --member serviceAccount:$AZURE_PIPELINES_PUBLISHER \
        --role roles/artifactregistry.admin
    
  7. Buat kunci akun layanan:

    gcloud iam service-accounts keys create azure-pipelines-publisher.json \
        --iam-account $AZURE_PIPELINES_PUBLISHER
    
    tr -d '\n' < azure-pipelines-publisher.json > azure-pipelines-publisher-oneline.json
    
  8. Lihat konten file kunci akun layanan:

    echo $(<azure-pipelines-publisher-oneline.json)
    

    Anda memerlukan kunci akun layanan di salah satu langkah berikut.

Membuat koneksi layanan untuk Google Container Registry

Di Azure Pipelines, buat koneksi layanan baru untuk Container Registry:

  1. Di menu DevOps Azure, pilih Project settings, lalu pilih Pipelines > Service connections.
  2. Klik Create service connection.
  3. Dari daftar, pilih Docker Registry, lalu klik Next.
  4. Dalam dialog, masukkan nilai untuk kolom berikut:
    • Jenis registry: Lainnya
    • Docker Registry: https://gcr.io/PROJECT_ID, ganti PROJECT_ID dengan nama project Anda (misalnya, https://gcr.io/azure-pipelines-test-project-12345).
    • Docker ID: _json_key
    • Sandi: Tempelkan konten azure-pipelines-publisher-oneline.json.
    • Nama koneksi layanan: gcr-tutorial
  5. Klik Simpan untuk membuat koneksi.

Membangun secara berkelanjutan

Sekarang Anda dapat menggunakan Azure Pipelines untuk menyiapkan continuous integration. Untuk setiap commit yang dikirim ke repositori Git, Azure Pipelines akan membangun kode dan mengemas artefak build ke dalam container Docker. Kemudian, container akan dipublikasikan ke Container Registry.

Repositori sudah berisi Dockerfile berikut:

.NET/Linux

#
# Copyright 2020 Google LLC
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

FROM mcr.microsoft.com/dotnet/aspnet:6.0
EXPOSE 8080

#------------------------------------------------------------------------------
# Copy publishing artifacts.
#------------------------------------------------------------------------------

WORKDIR /app
COPY CloudDemo.MvcCore/bin/Release/net6.0/publish/ /app/

ENV ASPNETCORE_URLS=http://0.0.0.0:8080

#------------------------------------------------------------------------------
# Run application in Kestrel.
#------------------------------------------------------------------------------

ENTRYPOINT ["dotnet", "CloudDemo.MvcCore.dll"]

.NET Framework/Windows

#
# Copyright 2020 Google LLC
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

FROM mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019
EXPOSE 80
SHELL ["powershell", "-command"]

#------------------------------------------------------------------------------
# Add LogMonitor so that IIS and Windows logs are emitted to STDOUT and can be 
# picked up by Docker/Kubernetes.
#
# See https://github.com/microsoft/windows-container-tools/wiki/Authoring-a-Config-File
# for details.
#------------------------------------------------------------------------------

ADD https://github.com/microsoft/windows-container-tools/releases/download/v1.1/LogMonitor.exe LogMonitor/
ADD LogMonitorConfig.json LogMonitor/

#------------------------------------------------------------------------------
# Copy publishing artifacts to webroot.
#------------------------------------------------------------------------------

ADD CloudDemo.Mvc/bin/Release/PublishOutput/ c:/inetpub/wwwroot/

#------------------------------------------------------------------------------
# Configure IIS using the helper functions from deployment.ps1.
#------------------------------------------------------------------------------

ADD deployment.ps1 /
RUN . /deployment.ps1; \
	Install-Iis; \
	Register-WebApplication -AppName "CloudDemo"; \
	Remove-Item /deployment.ps1

#------------------------------------------------------------------------------
# Run IIS, wrapped by LogMonitor.
#------------------------------------------------------------------------------

ENTRYPOINT ["C:\\LogMonitor\\LogMonitor.exe", "C:\\ServiceMonitor.exe", "w3svc"]

Sekarang Anda akan membuat pipeline baru yang menggunakan sintaksis YAML:

  1. Dengan menggunakan klien git command line atau Visual Studio, clone repositori Git baru Anda dan periksa cabang main.
  2. Di root repositori, buat file bernama azure-pipelines.yml.
  3. Salin kode berikut ke dalam file:

    .NET/Linux

    resources:
    - repo: self
      fetchDepth: 1
    pool:
      vmImage: ubuntu-20.04
    trigger:
    - main
    variables:
      TargetFramework: 'net6.0'
      BuildConfiguration: 'Release'
      DockerImageName: 'PROJECT_ID/clouddemo'
    steps:
    - task: DotNetCoreCLI@2
      displayName: Publish
      inputs:
        projects: 'applications/clouddemo/netcore/CloudDemo.MvcCore.sln'
        publishWebProjects: false
        command: publish
        arguments: '--configuration $(BuildConfiguration) --framework=$(TargetFramework)'
        zipAfterPublish: false
        modifyOutputPath: false
    - task: CmdLine@1
      displayName: 'Lock image version in deployment.yaml'
      inputs:
        filename: /bin/bash
        arguments: '-c "awk ''{gsub(\"CLOUDDEMO_IMAGE\", \"gcr.io/$(DockerImageName):$(Build.BuildId)\", $0); print}'' applications/clouddemo/netcore/deployment.yaml > $(build.artifactstagingdirectory)/deployment.yaml"'
    - task: PublishBuildArtifacts@1
      displayName: 'Publish Artifact'
      inputs:
        PathtoPublish: '$(build.artifactstagingdirectory)'
    - task: Docker@2
      displayName: 'Login to Artifact Registry'
      inputs:
        command: login
        containerRegistry: 'gcr-tutorial'
    - task: Docker@2
      displayName: 'Build and push image'
      inputs:
        Dockerfile: 'applications/clouddemo/netcore/Dockerfile'
        command: buildAndPush
        repository: '$(DockerImageName)'

    .NET Framework/Windows

    resources:
    - repo: self
      fetchDepth: 1
    pool:
      vmImage: windows-2019     # Matches WINDOWS_LTSC in GKE
      demands:
      - msbuild
      - visualstudio
    trigger:
    - master
    variables:
      Solution: 'applications/clouddemo/net4/CloudDemo.Mvc.sln'
      BuildPlatform: 'Any CPU'
      BuildConfiguration: 'Release'
      DockerImageName: 'PROJECT_ID/clouddemo'
    steps:
    - task: NuGetCommand@2
      displayName: 'NuGet restore'
      inputs:
        restoreSolution: '$(Solution)'
    - task: VSBuild@1
      displayName: 'Build solution'
      inputs:
        solution: '$(Solution)'
        msbuildArgs: '/p:DeployOnBuild=true /p:PublishProfile=FolderProfile'
        platform: '$(BuildPlatform)'
        configuration: '$(BuildConfiguration)'
    - task: PowerShell@2
      displayName: 'Lock image version in deployment.yaml'
      inputs:
        targetType: 'inline'
        script: '(Get-Content applications\clouddemo\net4\deployment.yaml) -replace "CLOUDDEMO_IMAGE","gcr.io/$(DockerImageName):$(Build.BuildId)" | Out-File -Encoding ASCII $(build.artifactstagingdirectory)\deployment.yaml'
    - task: PublishBuildArtifacts@1
      displayName: 'Publish Artifact'
      inputs:
        PathtoPublish: '$(build.artifactstagingdirectory)'
    - task: Docker@2
      displayName: 'Login to Artifact Registry'
      inputs:
        command: login
        containerRegistry: 'gcr-tutorial'
    - task: Docker@2
      displayName: 'Build and push image'
      inputs:
        Dockerfile: 'applications/clouddemo/net4/Dockerfile'
        command: buildAndPush
        repository: '$(DockerImageName)'

    Ganti PROJECT_ID dengan nama project Anda, lalu simpan file.

  4. Lakukan commit pada perubahan Anda dan kirimkan ke Azure Pipelines.

    Visual Studio

    1. Buka Team Explorer, lalu klik ikon Home.
    2. Klik Perubahan.
    3. Masukkan pesan commit seperti Add pipeline definition.
    4. Klik Commit All and Push.

    Command line

    1. Siapkan semua file yang diubah:

      git add -A
      
    2. Lakukan perubahan pada repositori lokal:

      git commit -m "Add pipeline definition"
      
    3. Kirim perubahan ke Azure DevOps:

      git push
      
  5. Di menu Azure DevOps, pilih Pipelines, lalu klik Create Pipeline.

  6. Pilih Azure Repos Git.

  7. Pilih repositori Anda.

  8. Di halaman Tinjau YAML pipeline Anda, klik Jalankan.

    Build baru dipicu. Proses build mungkin memerlukan waktu sekitar 6 menit.

  9. Untuk memverifikasi bahwa image telah dipublikasikan ke Container Registry, beralihlah ke project Anda di konsol Google Cloud , pilih Container Registry > Images, lalu klik clouddemo.

    Satu gambar dan tag gambar ini ditampilkan. Tag sesuai dengan ID numerik build yang dijalankan di Azure Pipelines.

Men-deploy secara berkelanjutan

Dengan Azure Pipelines yang otomatis membangun kode dan memublikasikan image Docker untuk setiap commit, Anda kini dapat mengalihkan perhatian ke deployment.

Tidak seperti sistem integrasi berkelanjutan lainnya, Azure Pipelines membedakan antara membangun dan men-deploy, serta menyediakan serangkaian alat khusus berlabel Release Management untuk semua tugas terkait deployment.

Pengelolaan Rilis Azure Pipelines dibangun berdasarkan konsep berikut:

  • Rilis mengacu pada sekumpulan artefak yang membentuk versi tertentu aplikasi Anda dan biasanya merupakan hasil dari proses build.
  • Deployment mengacu pada proses pengambilan rilis dan men-deploy-nya ke lingkungan tertentu.
  • Deployment melakukan serangkaian tugas, yang dapat dikelompokkan dalam tugas.
  • Tahapan memungkinkan Anda menyegmentasikan pipeline dan dapat digunakan untuk mengatur penerapan ke beberapa lingkungan, misalnya, lingkungan pengembangan dan pengujian.

Artefak utama yang dihasilkan oleh proses build CloudDemo adalah image Docker. Namun, karena image Docker dipublikasikan ke Container Registry, image tersebut berada di luar cakupan Azure Pipelines. Oleh karena itu, gambar tidak berfungsi dengan baik sebagai definisi rilis.

Untuk men-deploy ke Kubernetes, Anda juga memerlukan manifes, yang menyerupai daftar materi. Manifes tidak hanya menentukan resource yang seharusnya dibuat dan dikelola oleh Kubernetes, tetapi juga menentukan versi persis image Docker yang akan digunakan. Manifes Kubernetes sangat cocok untuk berfungsi sebagai artefak yang menentukan rilis di Azure Pipelines Release Management.

Mengonfigurasi deployment Kubernetes

Untuk menjalankan CloudDemo di Kubernetes, Anda memerlukan resource berikut:

  • Deployment yang menentukan satu pod yang menjalankan image Docker yang dihasilkan oleh build.
  • Layanan NodePort yang membuat pod dapat diakses oleh load balancer.
  • Ingress yang mengekspos aplikasi ke internet publik dengan menggunakan load balancer HTTP(S) Cloud.

Repositori sudah berisi manifes Kubernetes berikut yang menentukan resource ini:

.NET/Linux

#
# Copyright 2020 Google LLC
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

apiVersion: v1
kind: Service
metadata:
  name: clouddemo-netcore
spec:
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP
    name: http
  selector:
    app: clouddemo-netcore
  type: NodePort

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: clouddemo-netcore
spec:
  defaultBackend:
    service:
      name: clouddemo-netcore
      port:
        number: 80

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: clouddemo-netcore
spec:
  replicas: 2
  selector:
    matchLabels:
      app: clouddemo-netcore
  template:
    metadata:
      labels:
        app: clouddemo-netcore
    spec:
      containers:
      - name: clouddemo-netcore
        image: CLOUDDEMO_IMAGE
        ports:
          - containerPort: 8080
        livenessProbe:      # Used by deployment controller
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
        readinessProbe:     # Used by Ingress/GCLB
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 3
          periodSeconds: 5
        resources:
          limits:
            memory: 1024Mi
          requests:
            memory: 256Mi

.NET Framework/Windows

#
# Copyright 2020 Google LLC
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

apiVersion: v1
kind: Service
metadata:
  name: clouddemo-net4
  annotations:
    cloud.google.com/neg: '{"ingress": false}' # Disable NEG

spec:
  ports:
  - port: 80
    targetPort: 80
    protocol: TCP
    name: http
  selector:
    app: clouddemo-net4
  type: NodePort

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: clouddemo-net4
spec:
  defaultBackend:
    service:
      name: clouddemo-net4
      port:
        number: 80

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: clouddemo-net4
spec:
  replicas: 2
  selector:
    matchLabels:
      app: clouddemo-net4
  template:
    metadata:
      labels:
        app: clouddemo-net4
    spec:
      nodeSelector:
        kubernetes.io/os: windows
      containers:
      - name: clouddemo-net4
        image: CLOUDDEMO_IMAGE
        ports:
          - containerPort: 80
        livenessProbe:      # Used by deployment controller
          httpGet:
            path: /health
            port: 80
          initialDelaySeconds: 120
          periodSeconds: 5
        readinessProbe:     # Used by Ingress/GCLB
          httpGet:
            path: /health
            port: 80
          initialDelaySeconds: 10
          periodSeconds: 5
        resources:
          limits:
            memory: 1024Mi
          requests:
            memory: 256Mi

Menyiapkan lingkungan pengembangan dan produksi

Sebelum kembali ke Azure Pipelines Release Management, Anda harus membuat cluster GKE.

Membuat cluster GKE

  1. Kembali ke instance Cloud Shell Anda.

  2. Aktifkan GKE API untuk project Anda:

    gcloud services enable container.googleapis.com
  3. Buat cluster pengembangan menggunakan perintah berikut. Perhatikan bahwa proses ini mungkin memerlukan waktu beberapa menit:

    .NET/Linux

    gcloud container clusters create azure-pipelines-cicd-dev --enable-ip-alias
    

    .NET Framework/Windows

    gcloud container clusters create azure-pipelines-cicd-dev --enable-ip-alias
    
    gcloud container node-pools create azure-pipelines-cicd-dev-win \
        --cluster=azure-pipelines-cicd-dev \
        --image-type=WINDOWS_LTSC \
        --no-enable-autoupgrade \
        --machine-type=n1-standard-2
    
  4. Buat cluster produksi menggunakan perintah berikut. Perhatikan bahwa proses ini mungkin memerlukan waktu beberapa menit:

    .NET/Linux

    gcloud container clusters create azure-pipelines-cicd-prod --enable-ip-alias
    

    .NET Framework/Windows

    gcloud container clusters create azure-pipelines-cicd-prod --enable-ip-alias
    
    gcloud container node-pools create azure-pipelines-cicd-prod-win \
        --cluster=azure-pipelines-cicd-prod \
        --image-type=WINDOWS_LTSC \
        --no-enable-autoupgrade \
        --machine-type=n1-standard-2
    

Menghubungkan Azure Pipelines ke cluster pengembangan

Sama seperti Anda dapat menggunakan Azure Pipelines untuk terhubung ke registry Docker eksternal seperti Container Registry, Azure Pipelines mendukung integrasi cluster Kubernetes eksternal.

Anda dapat melakukan autentikasi ke Container Registry menggunakan akun layananGoogle Cloud , tetapi penggunaan akun layanan Google Cloud tidak didukung oleh Azure Pipelines untuk melakukan autentikasi dengan GKE. Sebagai gantinya, Anda harus menggunakan akun layanan Kubernetes.

Oleh karena itu, untuk menghubungkan Azure Pipelines ke cluster pengembangan, Anda harus membuat akun layanan Kubernetes terlebih dahulu.

  1. Di Cloud Shell, hubungkan ke cluster pengembangan:

    gcloud container clusters get-credentials azure-pipelines-cicd-dev
  2. Buat akun layanan Kubernetes untuk Azure Pipelines:

    kubectl create serviceaccount azure-pipelines-deploy
  3. Buat secret Kubernetes yang berisi kredensial token untuk Azure Pipelines:

    kubectl create secret generic azure-pipelines-deploy-token --type=kubernetes.io/service-account-token --dry-run -o yaml \
      | kubectl annotate --local -o yaml -f - kubernetes.io/service-account.name=azure-pipelines-deploy \
      | kubectl apply -f -
    
  4. Tetapkan peran cluster-admin ke akun layanan dengan membuat binding peran cluster:

    kubectl create clusterrolebinding azure-pipelines-deploy --clusterrole=cluster-admin --serviceaccount=default:azure-pipelines-deploy
  5. Tentukan alamat IP cluster:

    gcloud container clusters describe azure-pipelines-cicd-dev --format=value\(endpoint\)
    

    Anda akan memerlukan alamat ini sebentar lagi.

  6. Di menu Azure DevOps, pilih Project settings, lalu pilih Pipelines > Service connections.

  7. Klik Koneksi layanan baru.

  8. Pilih Kubernetes, lalu klik Berikutnya.

  9. Konfigurasi setelan berikut.

    • Authentication method: Service account.
    • URL Server: https://PRIMARY_IP. Ganti PRIMARY_IP dengan alamat IP yang Anda tentukan sebelumnya.
    • Secret: Secret Kubernetes yang Anda buat sebelumnya. Untuk mendapatkan Secret, jalankan perintah berikut, salin Secret, lalu salin Secret ke halaman Azure.
      kubectl get secret azure-pipelines-deploy-token -o yaml
    • Service connection name: azure-pipelines-cicd-dev.
  10. Klik Simpan.

Menghubungkan Azure Pipelines ke cluster produksi

Untuk menghubungkan Azure Pipelines ke cluster produksi, Anda dapat mengikuti pendekatan yang sama.

  1. Di Cloud Shell, hubungkan ke cluster produksi:

    gcloud container clusters get-credentials azure-pipelines-cicd-prod
  2. Buat akun layanan Kubernetes untuk Azure Pipelines:

    kubectl create serviceaccount azure-pipelines-deploy
  3. Tetapkan peran cluster-admin ke akun layanan dengan membuat binding peran cluster:

    kubectl create clusterrolebinding azure-pipelines-deploy --clusterrole=cluster-admin --serviceaccount=default:azure-pipelines-deploy
  4. Tentukan alamat IP cluster:

    gcloud container clusters describe azure-pipelines-cicd-prod --format=value\(endpoint\)
    

    Anda akan memerlukan alamat ini sebentar lagi.

  5. Di menu Azure DevOps, pilih Project settings, lalu pilih Pipelines > Service connections.

  6. Klik Koneksi layanan baru.

  7. Pilih Kubernetes, lalu klik Berikutnya.

  8. Konfigurasi setelan berikut:

    • Authentication method: Service account.
    • URL Server: https://PRIMARY_IP. Ganti PRIMARY_IP dengan alamat IP yang Anda tentukan sebelumnya.
    • Secret: Jalankan perintah berikut di Cloud Shell dan salin outputnya:
      kubectl get secret $(kubectl get serviceaccounts azure-pipelines-deploy -o custom-columns=":secrets[0].name") -o yaml
    • Service connection name: azure-pipelines-cicd-prod.
  9. Klik Simpan.

Mengonfigurasi pipeline rilis

Setelah menyiapkan infrastruktur GKE, Anda akan kembali ke Azure Pipelines untuk mengotomatiskan deployment, yang mencakup hal berikut:

  • Men-deploy ke lingkungan pengembangan.
  • Meminta persetujuan manual sebelum memulai deployment ke lingkungan produksi.
  • Men-deploy ke lingkungan produksi.

Membuat definisi rilis

Sebagai langkah pertama, buat definisi rilis baru.

  1. Di menu Azure DevOps, pilih Pipelines > Releases.
  2. Klik Pipeline baru.
  3. Dari daftar template, pilih Empty job.
  4. Saat Anda diminta untuk memasukkan nama panggung, masukkan Development.
  5. Di bagian atas layar, beri nama rilis CloudDemo-KubernetesEngine.
  6. Dalam diagram pipeline, di samping Artifacts, klik Add.
  7. Pilih Build dan tambahkan setelan berikut:

    • Jenis sumber: Build
    • Sumber (pipeline build): Pilih definisi build (hanya boleh ada satu opsi)
    • Versi default: Latest
    • Alias Sumber: manifest
  8. Klik Tambahkan.

  9. Di kotak Artifact, klik Continuous deployment trigger (ikon petir) untuk menambahkan pemicu deployment.

  10. Di bagian Pemicu deployment berkelanjutan, setel tombol ke Diaktifkan.

  11. Klik Simpan.

  12. Masukkan komentar jika Anda mau, lalu konfirmasi dengan mengklik Oke.

    Pipeline akan ditampilkan seperti berikut.

    Screenshot pipeline yang diperbarui di Azure Pipelines

Men-deploy ke cluster pengembangan

Setelah definisi rilis dibuat, Anda kini dapat mengonfigurasi deployment ke cluster pengembangan GKE.

  1. Di menu, beralihlah ke tab Tugas.
  2. Klik Agent job dan konfigurasi setelan berikut:

    • Agent pool: Azure Pipelines
    • Spesifikasi agen: ubuntu-18.04
  3. Di samping Tugas agen, klik Tambahkan tugas ke tugas agen untuk menambahkan langkah ke fase.

  4. Pilih tugas Deploy to Kubernetes, lalu klik Add.

  5. Klik tugas yang baru ditambahkan dan konfigurasi setelan berikut:

    • Nama tampilan: Deploy
    • Tindakan: deploy
    • Koneksi layanan Kubernetes: azure-pipelines-cicd-dev
    • Namespace: default
    • Strategi: Tidak ada
    • Manifest: manifest/drop/deployment.yaml
  6. Klik Simpan.

  7. Masukkan komentar jika Anda mau, lalu konfirmasi dengan mengklik Oke.

Men-deploy ke cluster produksi

Terakhir, Anda mengonfigurasi deployment ke cluster produksi GKE.

  1. Di menu, beralihlah ke tab Pipeline.
  2. Di kotak Stages, pilih Add > New stage.
  3. Dari daftar template, pilih Empty job.
  4. Saat Anda diminta untuk memasukkan nama panggung, masukkan Production.
  5. Klik ikon petir pada tahap yang baru dibuat.
  6. Konfigurasi setelan berikut:

    • Pilih pemicu: Setelah tahap
    • Tahapan: Dev
    • Persetujuan sebelum deployment: (diaktifkan)
    • Pemberi persetujuan: Pilih nama pengguna Anda sendiri.

    Pipeline sekarang terlihat seperti ini:

    Screenshot pipeline yang diperbarui di Azure Pipelines

  7. Beralihlah ke tab Tugas.

  8. Arahkan kursor ke tab Tasks, lalu pilih Tasks > Production.

  9. Klik Agent job dan konfigurasi setelan berikut:

    • Agent pool: Azure Pipelines
    • Spesifikasi agen: ubuntu-18.04
  10. Klik Tambahkan tugas ke pekerjaan agen untuk menambahkan langkah ke fase.

  11. Pilih tugas Deploy to Kubernetes, lalu klik Add.

  12. Klik tugas yang baru ditambahkan dan konfigurasi setelan berikut:

    • Nama tampilan: Deploy
    • Tindakan: deploy
    • Koneksi layanan Kubernetes: azure-pipelines-cicd-prod
    • Namespace: default
    • Strategi: Tidak ada
    • Manifest: manifest/drop/deployment.yaml
  13. Klik Simpan.

  14. Masukkan komentar jika Anda mau, lalu konfirmasi dengan mengklik Oke.

Menjalankan pipeline

Setelah mengonfigurasi seluruh pipeline, Anda dapat mengujinya dengan melakukan perubahan kode sumber:

  1. Di komputer lokal Anda, buka file Index.cshtml dari repositori Git yang Anda clone sebelumnya:

    .NET/Linux

    File tersebut terletak di applications\clouddemo\netcore\CloudDemo.MvcCore\Views\Home\

    .NET Framework/Windows

    File tersebut terletak di applications\clouddemo\net4\CloudDemo.Mvc\Views\Home\

  2. Di baris 26, ubah nilai ViewBag.Title dari Home Page menjadi This app runs on GKE.

  3. Lakukan commit pada perubahan, lalu kirimkan ke Azure Pipelines.

    Visual Studio

    1. Buka Team Explorer, lalu klik ikon Home.
    2. Klik Perubahan.
    3. Masukkan pesan commit seperti Change site title.
    4. Klik Commit All and Push.

    Command line

    1. Siapkan semua file yang diubah:

      git add -A
      
    2. Lakukan perubahan pada repositori lokal:

      git commit -m "Change site title"
      
    3. Kirim perubahan ke Azure Pipelines:

      git push
      
  4. Di menu Azure DevOps, pilih Pipelines. Build dipicu.

  5. Setelah build selesai, pilih Pipelines > Releases. Proses rilis dimulai.

  6. Klik Release-1 untuk membuka halaman detail, lalu tunggu hingga status tahap Development berubah menjadi Succeeded.

  7. Di Google Cloud konsol, pilih Kubernetes Engine > Services & Ingress > Ingress.

  8. Cari layanan Ingress untuk cluster azure-pipelines-cicd-dev, lalu tunggu hingga statusnya berubah menjadi Ok. Proses ini dapat memerlukan waktu beberapa menit.

  9. Buka link di kolom Frontend pada baris yang sama. Anda mungkin melihat error pada awalnya karena load balancer memerlukan waktu beberapa menit agar tersedia. Setelah siap, amati bahwa CloudDemo telah di-deploy dan menggunakan judul kustom.

  10. Di Azure Pipelines, klik tombol Approve yang ada di bagian Prod stage untuk mempromosikan deployment ke lingkungan produksi.

    Jika tidak melihat tombol tersebut, Anda mungkin perlu menyetujui atau menolak rilis sebelumnya terlebih dahulu.

  11. Masukkan komentar jika Anda mau, lalu konfirmasi dengan mengklik Setujui.

  12. Tunggu hingga status lingkungan Prod berubah menjadi Succeeded. Anda mungkin perlu memuat ulang halaman secara manual di browser.

  13. Di konsol Google Cloud , muat ulang halaman Services & Ingress.

  14. Cari layanan Ingress untuk cluster azure-pipelines-cicd-prod dan tunggu hingga statusnya berubah menjadi Ok. Proses ini dapat memerlukan waktu beberapa menit.

  15. Buka link di kolom Frontend pada baris yang sama. Sekali lagi, Anda mungkin melihat error pada awalnya karena load balancer memerlukan waktu beberapa menit agar tersedia. Setelah siap, Anda akan melihat aplikasi CloudDemo dengan judul kustom lagi, kali ini berjalan di cluster produksi.

Pembersihan

Agar tidak menimbulkan biaya lebih lanjut setelah Anda menyelesaikan tutorial ini, hapus entitas yang telah Anda buat.

Menghapus project Azure Pipelines

Untuk menghapus project Azure Pipelines, lihat dokumentasi Azure DevOps Services. Menghapus project Azure Pipelines akan menyebabkan semua perubahan kode sumber hilang.

Menghapus Google Cloud pengembangan dan project

  1. Di Konsol Google Cloud , buka halaman Manage resources.

    Buka Kelola resource

  2. Pada daftar project, pilih project yang ingin Anda hapus, lalu klik Delete.
  3. Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.

Langkah berikutnya