Project Icon

rules_gitops

Bazel规则集实现Kubernetes部署自动化

rules_gitops是一个Bazel规则集,用于实现容器构建和Git驱动部署的无缝集成。它自动处理镜像推送、替换和Kustomize应用,并管理对象引用的内容寻址。该项目支持将生成的Kubernetes清单应用到集群或版本控制系统,简化了基于GitOps的部署流程。

Bazel GitOps Rules

CI

Bazel GitOps Rules provides tooling to bridge the gap between Bazel (for hermetic, reproducible, container builds) and continuous, git-operation driven, deployments. Users author standard kubernetes manifests and kustomize overlays for their services. Bazel GitOps Rules handles image push and substitution, applies necessary kustomizations, and handles content addressed substitutions of all object references (configmaps, secrets, etc). Bazel targets are exposed for applying the rendered manifest directly to a Kubernetes cluster, or into version control facilitating deployment via Git operations.

Bazel GitOps Rules is an alternative to rules_k8s. The main differences are:

  • Utilizes and integrates the full set of Kustomize capabilities for generating manifests.
  • Implements GitOps target.
  • Supports personal namespace deployments.
  • Provides integration test setup utility.
  • Speeds up deployments iterations:
    • The results manifests are rendered without pushing containers.
    • Pushes all the images in parallel.
  • Provides an utility that creates GitOps pull requests.

Rules

Guides

Installation

From the release you wish to use: https://github.com/adobe/rules_gitops/releases copy the WORKSPACE snippet into your WORKSPACE file.

k8s_deploy

The k8s_deploy creates rules that produce the .apply and .gitops targets k8s_deploy is defined in k8s.bzl. k8s_deploy takes the files listed in the manifests, patches, and configmaps_srcs attributes and combines (renders) them into one YAML file. This happens when you bazel build or bazel run a target created by the k8s_deploy. The file is created at bazel-bin/path/to/package/name.yaml. When you run a .apply target, it runs kubectl apply on this file. When you run a .gitops target, it copies this file to the appropriate location in the same os separate repository.

For example, let's look at the example's k8s_deploy. We can peek at the file containing the rendered K8s manifests:

cd examples
bazel run //helloworld:mynamespace.show

When you run bazel run ///helloworld:mynamespace.apply, it applies this file into your personal ({BUILD_USER}) namespace. Viewing the rendered files with .show can be useful for debugging issues with invalid or misconfigured manifests.

ParameterDefaultDescription
clusterNoneThe name of the cluster in which these manifests will be applied.
namespaceNoneThe target namespace to assign to all manifests. Any namespace value in the source manifests will be replaced or added if not specified.
user{BUILD_USER}The user passed to kubectl in .apply rule. Must exist in users ~/.kube/config
configmaps_srcsNoneA list of files (of any type) that will be combined into configmaps. See Generating Configmaps.
configmaps_renamingNoneConfigmaps/Secrets renaming policy. Could be None or 'hash'. 'hash' renaming policy is used to add a unique suffix to the generated configmap or secret name. All references to the configmap or secret in other manifests will be replaced with the generated name.
secrets_srcsNoneA list of files (of any type) that will be combined into a secret similar to configmaps.
manifestsglob(['*.yaml','*.yaml.tpl'])A list of base manifests. See Base Manifests and Overlays.
name_prefixNoneAdds prefix to the names of all resources defined in manifests.
name_suffixNoneAdds suffix to the names of all resources defined in manifests.
patchesNoneA list of patch files to overlay the base manifests. See Base Manifests and Overlays.
image_name_patchesNoneA dict of image names that will be replaced with new ones. See kustomization images.
image_tag_patchesNoneA dict of image names which tags be replaced with new ones. See kustomization images.
substitutionsNoneDoes parameter substitution in all the manifests (including configmaps). This should generally be limited to "CLUSTER" and "NAMESPACE" only. Any other replacements should be done with overlays.
configurations[]A list of files with kustomize configurations.
prefix_suffix_app_labelsFalseAdd the bundled configuration file allowing adding suffix and prefix to labels app and app.kubernetes.io/name and respective selector in Deployment.
common_labels{}A map of labels that should be added to all objects and object templates.
common_annotations{}A map of annotations that should be added to all objects and object templates.
start_tag"{{"The character start sequence used for substitutions.
end_tag"}}"The character end sequence used for substitutions.
deps[]A list of dependencies used to drive k8s_deploy functionality (i.e. deps_aliases).
deps_aliases{}A dict of labels of file dependencies. File dependency contents are available for template expansion in manifests as {{imports.<label>}}. Each dependency in this dictionary should be present in the deps attribute.
objects[]A list of other instances of k8s_deploy that this one depends on. See Adding Dependencies.
images{}A dict of labels of Docker images. See Injecting Docker Images.
image_digest_tagFalseA flag for whether or not to tag the image with the container digest.
image_registrydocker.ioThe registry to push images to.
image_repositoryNoneThe repository to push images to. By default, this is generated from the current package path.
image_repository_prefixNoneAdd a prefix to the image_repository. Can be used to upload the images in
image_pushes[]A list of labels implementing K8sPushInfo referring image uploaded into registry. See Injecting Docker Images.
release_branch_prefixmasterA git branch name/prefix. Automatically run GitOps while building this branch. See GitOps and Deployment.
deployment_branchNoneAutomatic GitOps output will appear in a branch and PR with this name. See GitOps and Deployment.
gitops_pathcloudPath within the git repo where gitops files get generated into
tags[]See Bazel docs on tags.
visibilityDefault_visibilityChanges the visibility of all rules generated by this macro. See Bazel docs on visibility.

Base Manifests and Overlays

The manifests listed in the manifests attribute are the base manifests used by the deployment. This is where the important manifests like Deployments, Services, etc. are listed.

The base manifests will be modified by most of the other k8s_deploy attributes like substitutions and images. Additionally, they can be modified to configure them different clusters/namespaces/etc. using overlays.

To demonstrate, let's go over hypothetical multi cluster deployment.

Here is the fragment of the k8s_deploy rule that is responsible for generating manifest variants per CLOUD, CLUSTER, and NAMESPACE :

k8s_deploy(
    ...
    manifests = glob([                 # (1)
      "manifests/*.yaml",
      "manifests/%s/*.yaml" % (CLOUD),
    ]),
    patches = glob([                   # (2)
      "overlays/*.yaml",
      "overlays/%s/*.yaml" % (CLOUD),
      "overlays/%s/%s/*.yaml" % (CLOUD, NAMESPACE),
      "overlays/%s/%s/%s/*.yaml" % (CLOUD, NAMESPACE, CLUSTER),
    ]),
    ...
)

The manifests list (1) combines common base manifests and CLOUD specific manifests.

manifests
├── aws
│   └── pvc.yaml
├── onprem
│   ├── pv.yaml
│   └── pvc.yaml
├── deployment.yaml
├── ingress.yaml
└── service.yaml

Here we see that aws and onprem clouds have different persistence configurations aws/pvc.yaml and onprem/pvc.yaml.

The patches list (2) requires more granular configuration that introduces 3 levels of customization: CLOUD, NAMESPACE, and CLUSTER. Each manifest fragment in the overlays subtree applied as strategic merge patch update operation.

overlays
├── aws
│   ├── deployment.yaml
│   ├── prod
│   │   ├── deployment.yaml
│   │   └── us-east-1
│   │       └── deployment.yaml
│   └── uat
│       └── deployment.yaml
└── onprem
    ├── prod
    │   ├── deployment.yaml
    │   └── us-east
    │       └── deployment.yaml
    └── uat
        └── deployment.yaml

That looks like a lot. But lets try to decode what is happening here:

  1. aws/deployment.yaml adds persistent volume reference specific to all AWS deployments.
  2. aws/prod/deployment.yaml modifies main container CPU and memory requirements in production configurations.
  3. aws/prod/us-east-1/deployment.yaml adds monitoring sidecar.

Generating Configmaps

Configmaps are a special case of manifests. They can be rendered from a collection of files of any kind (.yaml, .properties, .xml, .sh, whatever). Let's use hypothetical Grafana deployment as an example:

[
    k8s_deploy(
        name = NAME,
        cluster = CLUSTER,
        configmaps_srcs = glob([                 # (1)
            "configmaps/%s/**/*" % CLUSTER
        ]),
        configmaps_renaming = 'hash',            # (2)

        ...
    )
    for NAME, CLUSTER, NAMESPACE in [
        ("mynamespace", "dev", "{BUILD_USER}"),  # (3)
        ("prod-grafana", "prod", "prod"),        # (4)
    ]
]

Here we generate two k8s_deploy targets, one for mynamespace (3), another for production deployment (4).

The directory structure of configmaps looks like this:

grafana
└── configmaps
    ├── dev
    │   └── grafana
    │       └── ldap.toml
    └── prod
        └── grafana
            └── ldap.toml

The configmaps_srcs parameter (1) will get resolved into the patterns configmaps/dev/**/* and configmaps/prod/**/*. The result of rendering the manifests bazel run //grafana:prod-grafana.show will have following manifest fragment:

apiVersion: v1
data:
  ldap.toml: |
    [[servers]]
    ...
kind: ConfigMap
metadata:
  name: grafana-k75h878g4f
  namespace: ops-prod

The name of directory on the first level of glob patten grafana become the configmap name. The ldap.toml file on the next level were embedded into the configmap.

In this example, the configmap renaming policy (2) is set to hash, so the configmap's name appears as grafana-k75h878g4f. (If the renaming policy was None, the configmap's name would remain as grafana.) All the references to the grafana configmap in other manifests are replaced with the generated name:

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      volumes:
      ...
      - configMap:
          items:
          - key: ldap.toml
            path: ldap.toml
          name: grafana-k75h878g4f
        name: grafana-ldap

Injecting Docker Images

Third-party Docker images can be referenced directly in K8s manifests, but for most apps, we need to run our own images. The images are built in the Bazel build pipeline using rules_docker. For example, the java_image rule creates an image of a Java application from Java source code, dependencies, and configuration.

Here's a (very contrived) example of how this ties in with k8s_deploy. Here's the BUILD file located in the package //examples:

java_image(
    name = "helloworld_image",
    srcs = glob(["*.java"]),
    ...
)
k8s_deploy(
    name = "helloworld",
    manifests = ["helloworld.yaml"],
    images = {
        "helloworld_image": ":helloworld_image",  # (1)
    }
)

And here's helloworld.yaml:

apiVersion: v1
kind: Pod
metadata:
  name: helloworld
spec:
  containers:
    - image: //examples:helloworld_image  # (2)

There images attribute dictionary (1) defines the images available for the substitution. The manifest file references the fully qualified image target path //examples:helloworld_image (2).

The image key value in the dictionary is used as an image push identifier. The best practice (as provided in the example) is to use image key that matches the label name of the image target.

When we bazel build the example, the rendered manifest will look something like this:

apiVersion: v1
kind: Pod
metadata:
  name: helloworld
spec:
  containers:
    - image: registry.example.com/examples/helloworld_image@sha256:c94d75d68f4c1b436f545729bbce82774fda07

The image substitution using an images key is supported, but not recommended (this functionality might be removed in the future). For example, helloworld.yaml can reference helloworld_image:

apiVersion: v1
kind: Pod
metadata:
  name: helloworld
spec:
  containers:
    - image: helloworld_image

Image substitutions for Custom Resource Definitions (CRD) resources could also use target references directly. Their digests are available through string substitution. For example,

apiVersion: v1
kind: MyCrd
metadata:
  name: my_crd
  labels:
    app_label_image_digest: "{{//examples:helloworld_image.digest}}"
    app_label_image_short_digest: "{{//examples:helloworld_image.short-digest}}"
spec:
  image: "{{//examples:helloworld_image}}"

would become

apiVersion: v1
kind: MyCrd
metadata:
  name: my_crd
  labels:
    app_label_image_digest: "e6d465223da74519ba3e2b38179d1268b71a72f"
    app_label_image_short_digest: "e6d465223d"
spec:
  image: registry.example.com/examples/helloworld_image@sha256:e6d465223da74519ba3e2b38179d1268b71a72f

An all examples above the image: URL points to the helloworld_image in the private Docker registry. The image is uploaded to the registry before any .apply or .gitops target is executed. See

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号