Version: v1.3

GitOps

This section will introduce how to use KubeVela in GitOps environment and why.

This section is only apply to CLI, you need to enable the fluxcd addon.

GitOps is a continuous delivery method that allows developers to automatically deploy applications by changing code and declarative configurations in a Git repository, with Git-centric operations such as PR and commit. For detailed benefits of GitOps, please check this article.

KubeVela as an declarative application delivery control plane can be naturally used in GitOps approach, and this will provide below extra bonus to end users alongside with GitOps benefits:

  • application delivery workflow (CD pipeline)
    • i.e. KubeVela supports pipeline style application delivery process in GitOps, instead of simply declaring final status;
  • handling deployment dependencies and designing typologies (DAG);
  • unified higher level abstraction atop various GitOps tools’ primitives;
  • declare, provision and consume cloud resources in unified application definition;
  • various out-of-box deployment strategies (Canary, Blue-Green …);
  • various out-of-box hybrid/multi-cloud deployment policies (placement rule, cluster selectors etc.);
  • Kustomize-style patch for multi-env deployment without the need to learn Kustomize at all;
  • … and much more.

In this section, we will introduce steps of using KubeVela directly in GitOps approach.

This article will separate into two perspectives:

  1. For platform administrators/SREs, they can update the config in Git repo. It will trigger automated re-deployment.

  2. For developers, they can update the app source code and then push it to Git. It will trigger building latest image and re-deployment.

Note: you can also use it with existing tools such as ArgoCD with similar steps, detailed guides will be added in following releases.

Platform administrators/SREs prepares the Git repo for operational config. Every config change will be traceable by that. KubeVela will watch the repo and apply changes to the clusters.

alt

The configuration files are from the Example Repo.

In this example, we will deploy an application and a database, the application uses the database to store data.

The structure of the config repository looks below:

  • The clusters/ contains the GitOps config. It will command KubeVela to watch the specified repo and apply latest changes.
  • The apps/ contains the Application yaml for deploying the user-facing app.
  • The infrastructure/ contains infrastructure tools, i.e. MySQL database.
  1. ├── apps
  2. └── my-app.yaml
  3. ├── clusters
  4. ├── apps.yaml
  5. └── infra.yaml
  6. └── infrastructure
  7. └── mysql.yaml

KubeVela recommends using the directory structure above to manage your GitOps repository. clusters/ holds the associated KubeVela GitOps configuration that need to be applied to cluster manually, apps/ holds your application and infrastructure/ holds your base configuration. By separating applications from basic configurations, you can manage your deployment environment more reasonably and isolate application changes.

The clusters/ is the initialize configuration directory for KubeVela GitOps.

Below is how the clusters/infra.yaml looks like:

  1. apiVersion: core.oam.dev/v1beta1
  2. kind: Application
  3. metadata:
  4. name: infra
  5. spec:
  6. components:
  7. - name: database-config
  8. type: kustomize
  9. properties:
  10. repoType: git
  11. # replace it with your repo url
  12. url: https://github.com/FogDong/KubeVela-GitOps-Infra-Demo
  13. # replace it with your git secret if it's a private repo
  14. # secretRef: git-secret
  15. # the pull interval time, set to 10m since the infrastructure is steady
  16. pullInterval: 10m
  17. git:
  18. # the branch name
  19. branch: main
  20. # the path to sync
  21. path: ./infrastructure

apps.yaml and infra.yaml in clusters/ are similar. Their difference is to watch different directories. In apps.yaml, the properties.path will be ./apps.

Apply the files in clusters/ manually. They will sync the files in infrastructure/ and apps/ dir of the Git repo.

The file in apps/ is a simple application with database information and Ingress. The app serves HTTP service and connects to a MySQL database. In the ‘/‘ path, it will display the version in the code; in the /db path, it will list the data in database.

  1. apiVersion: core.oam.dev/v1beta1
  2. kind: Application
  3. metadata:
  4. name: my-app
  5. namespace: default
  6. spec:
  7. components:
  8. - name: my-server
  9. type: webservice
  10. properties:
  11. image: <your image address> # {"$imagepolicy": "default:apps"}
  12. port: 8088
  13. env:
  14. - name: DB_HOST
  15. value: mysql-cluster-mysql.default.svc.cluster.local:3306
  16. - name: DB_PASSWORD
  17. valueFrom:
  18. secretKeyRef:
  19. name: mysql-secret
  20. key: ROOT_PASSWORD
  21. traits:
  22. - type: ingress
  23. properties:
  24. domain: testsvc.example.com
  25. http:
  26. /: 8088

The infrastructure/ contains the config of some infrastructures like database. In the following, we will use MySQL operator to deploy a MySQL cluster.

Notice that there must be a secret in your cluster with MySQL password specified in key ROOT_PASSWORD.

  1. apiVersion: core.oam.dev/v1beta1
  2. kind: Application
  3. metadata:
  4. name: mysql
  5. namespace: default
  6. spec:
  7. components:
  8. - name: mysql-controller
  9. type: helm
  10. properties:
  11. repoType: helm
  12. url: https://presslabs.github.io/charts
  13. chart: mysql-operator
  14. version: "0.4.0"
  15. - name: mysql-cluster
  16. type: raw
  17. dependsOn:
  18. - mysql-controller
  19. properties:
  20. apiVersion: mysql.presslabs.org/v1alpha1
  21. kind: MysqlCluster
  22. metadata:
  23. name: mysql-cluster
  24. spec:
  25. replicas: 1
  26. # replace it with your secret
  27. secretName: mysql-secret

After storing bellow files in the Git config repo, we need to apply the GitOps config files in clusters/ manually.

First, apply the clusters/infra.yaml to cluster, we can see that the MySQL in infrastructure/ is automatically deployed:

  1. vela up -f clusters/infra.yaml
  1. $ vela ls
  2. APP COMPONENT TYPE TRAITS PHASE HEALTHY STATUS CREATED-TIME
  3. infra database-config kustomize running healthy 2021-09-26 20:48:09 +0800 CST
  4. mysql mysql-controller helm running healthy 2021-09-26 20:48:11 +0800 CST
  5. └─ mysql-cluster raw running healthy 2021-09-26 20:48:11 +0800 CST

Apply the clusters/apps.yaml to cluster, we can see that the application in apps/ is automatically deployed:

  1. vela up -f clusters/apps.yaml
  1. APP COMPONENT TYPE TRAITS PHASE HEALTHY STATUS CREATED-TIME
  2. apps apps kustomize running healthy 2021-09-27 16:55:53 +0800 CST
  3. infra database-config kustomize running healthy 2021-09-26 20:48:09 +0800 CST
  4. my-app my-server webservice ingress running healthy 2021-09-27 16:55:55 +0800 CST
  5. mysql mysql-controller helm running healthy 2021-09-26 20:48:11 +0800 CST
  6. └─ mysql-cluster raw running healthy 2021-09-26 20:48:11 +0800 CST

By deploying the KubeVela GitOps config files, we now automatically apply the application and database in cluster.

curl the Ingress of the app, we can see that the current version is 0.1.5 and the application is connected to the database successfully:

  1. $ kubectl get ingress
  2. NAME CLASS HOSTS ADDRESS PORTS AGE
  3. my-server <none> testsvc.example.com <ingress-ip> 80 162m
  4. $ curl -H "Host:testsvc.example.com" http://<ingress-ip>
  5. Version: 0.1.5
  6. $ curl -H "Host:testsvc.example.com" http://<ingress-ip>/db
  7. User: KubeVela
  8. Description: It's a test user

After the first deployment, we can modify the files in config repo to update the applications in the cluster.

Modify the domain of the application’s Ingress:

  1. ...
  2. traits:
  3. - type: ingress
  4. properties:
  5. domain: kubevela.example.com
  6. http:
  7. /: 8089

Check the Ingress in cluster after a while:

  1. NAME CLASS HOSTS ADDRESS PORTS AGE
  2. my-server <none> kubevela.example.com <ingress-ip> 80 162m

The host of the Ingress has been updated successfully!

In this way, we can edit the files in the Git repo to update the cluster.

Developers writes the application source code and push it to a Git repo (aka app repo). Once app repo updates, the CI will build the image and push it to the image registry. KubeVela watches the image registry, and updates the image in config repo. Finally, it will apply the config to the cluster.

User can update the configuration in the cluster automatically when the code is updated.

alt

Setup a Git repository with source code and Dockerfile.

The app serves HTTP service and connects to a MySQL database. In the ‘/‘ path, it will display the version in the code; in the /db path, it will list the data in database.

  1. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  2. _, _ = fmt.Fprintf(w, "Version: %s\n", VERSION)
  3. })
  4. http.HandleFunc("/db", func(w http.ResponseWriter, r *http.Request) {
  5. rows, err := db.Query("select * from userinfo;")
  6. if err != nil {
  7. _, _ = fmt.Fprintf(w, "Error: %v\n", err)
  8. }
  9. for rows.Next() {
  10. var username string
  11. var desc string
  12. err = rows.Scan(&username, &desc)
  13. if err != nil {
  14. _, _ = fmt.Fprintf(w, "Scan Error: %v\n", err)
  15. }
  16. _, _ = fmt.Fprintf(w, "User: %s \nDescription: %s\n\n", username, desc)
  17. }
  18. })
  19. if err := http.ListenAndServe(":8088", nil); err != nil {
  20. panic(err.Error())
  21. }

In this tutorial, we will setup a CI pipeline using GitHub Actions to build the image and push it to a registry. The code and configuration files are from the Example Repo.

After the new image is pushed to the image registry, KubeVela will be notified and update the Application file in the Git repository and cluster. Therefore, we need a secret with Git information for KubeVela to commit to the Git repository. Fill the following yaml files with your password and apply it to the cluster:

  1. apiVersion: v1
  2. kind: Secret
  3. metadata:
  4. name: my-secret
  5. type: kubernetes.io/basic-auth
  6. stringData:
  7. username: <your username>
  8. password: <your password>

The configuration repository is almost the same as the previous configuration, you only need to add the image registry config to the file. For more details, please refer to Example Repository.

Add the config of image registry in clusters/apps.yaml, it listens for image updates in the image registry:

  1. ...
  2. imageRepository:
  3. image: <your image>
  4. # if it's a private image registry, use `kubectl create secret docker-registry` to create the secret
  5. # secretRef: imagesecret
  6. filterTags:
  7. # filter the image tag
  8. pattern: '^master-[a-f0-9]+-(?P<ts>[0-9]+)'
  9. extract: '$ts'
  10. # use the policy to sort the latest image tag and update
  11. policy:
  12. numerical:
  13. order: asc
  14. # add more commit message
  15. commitMessage: "Image: {{range .Updated.Images}}{{println .}}{{end}}"

Modify the image field in apps/my-app.yaml and add annotation # {"$imagepolicy": "default:apps"}. Notice that KubeVela will only be able to modify the image field if the annotation is added after the field. default:apps is namespace:name of the GitOps config file above.

  1. spec:
  2. components:
  3. - name: my-server
  4. type: webservice
  5. properties:
  6. image: ghcr.io/fogdong/test-fog:master-cba5605f-1632714412 # {"$imagepolicy": "default:apps"}

After update the files in clusters/ to cluster, we can then update the application by modifying the code.

Change the Version to 0.1.6 and modify the data in database:

  1. const VERSION = "0.1.6"
  2. ...
  3. func InsertInitData(db *sql.DB) {
  4. stmt, err := db.Prepare(insertInitData)
  5. if err != nil {
  6. panic(err)
  7. }
  8. defer stmt.Close()
  9. _, err = stmt.Exec("KubeVela2", "It's another test user")
  10. if err != nil {
  11. panic(err)
  12. }
  13. }

Commit the change to the Git Repository, we can see that our CI pipelines has built the image and push it to the image registry.

KubeVela will listen to the image registry and update the apps/my-app.yaml in Git Repository with the latest image tag.

We can see that there is a commit form kubevelabot, the commit message is always with a prefix Update image automatically. You can use format like {{range .Updated.Images}}{{println .}}{{end}} to specify the image name in the commitMessage field.

alt

Note that if you want to put the code and config in the same repository, you need to filter out the commit from KubeVela in CI configuration like below to avoid the repeat build of pipeline.

  1. jobs:
  2. publish:
  3. if: "!contains(github.event.head_commit.message, 'Update image automatically')"

Re-check the Application in cluster, we can see that the image of the my-app has been updated after a while.

KubeVela polls the latest information from the code and image repo periodically (at an interval that can be customized):

  • When the Application file in the Git repository is updated, KubeVela will update the Application in the cluster based on the latest configuration.
  • When a new tag is added to the image registry, KubeVela will filter out the latest tag based on your policy and update it to Git repository. When the files in the repository are updated, KubeVela repeats the first step and updates the files in the cluster, thus achieving automatic deployment.

We can curl to Ingress to see the current version and data:

  1. $ kubectl get ingress
  2. NAME CLASS HOSTS ADDRESS PORTS AGE
  3. my-server <none> kubevela.example.com <ingress-ip> 80 162m
  4. $ curl -H "Host:kubevela.example.com" http://<ingress-ip>
  5. Version: 0.1.6
  6. $ curl -H "Host:kubevela.example.com" http://<ingress-ip>/db
  7. User: KubeVela
  8. Description: It's a test user
  9. User: KubeVela2
  10. Description: It's another test user

The Version has been updated successfully! Now we’re done with everything from changing the code to automatically applying to the cluster.

For platform admins/SREs, they update the config repo to operate the application and infrastructure. KubeVela will synchronize the config to the cluster, simplifying the deployment process.

For end users/developers, they write the source code, push it to Git, and then re-deployment will happen. It will make CI to build the image. KubeVela will then update the image field and apply the deployment config.

By integrating with GitOps, KubeVela helps users speed up deployment and simplify continuous deployment.

Last updated on Nov 1, 2022 by Tianxin Dong