{"id":30227258,"url":"https://github.com/adobe/rules_gitops","last_synced_at":"2025-08-14T18:03:11.578Z","repository":{"id":40462157,"uuid":"245190460","full_name":"adobe/rules_gitops","owner":"adobe","description":"This repository contains rules for continuous, GitOps driven Kubernetes deployments.","archived":false,"fork":false,"pushed_at":"2025-08-12T09:04:42.000Z","size":9194,"stargazers_count":190,"open_issues_count":33,"forks_count":46,"subscribers_count":11,"default_branch":"main","last_synced_at":"2025-08-12T14:53:16.904Z","etag":null,"topics":["bazel","bazel-rules","deployment","docker","docker-image","gitops","k8s","kubernetes","kustomize"],"latest_commit_sha":null,"homepage":"","language":"Starlark","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/adobe.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-03-05T14:52:31.000Z","updated_at":"2025-08-04T19:34:49.000Z","dependencies_parsed_at":"2024-04-08T16:43:08.213Z","dependency_job_id":"84111671-5619-4737-b642-26d365071494","html_url":"https://github.com/adobe/rules_gitops","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"purl":"pkg:github/adobe/rules_gitops","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adobe%2Frules_gitops","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adobe%2Frules_gitops/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adobe%2Frules_gitops/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adobe%2Frules_gitops/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/adobe","download_url":"https://codeload.github.com/adobe/rules_gitops/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adobe%2Frules_gitops/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270165717,"owners_count":24538430,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-12T02:00:09.011Z","response_time":80,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bazel","bazel-rules","deployment","docker","docker-image","gitops","k8s","kubernetes","kustomize"],"created_at":"2025-08-14T18:01:12.198Z","updated_at":"2025-08-14T18:03:11.516Z","avatar_url":"https://github.com/adobe.png","language":"Starlark","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Bazel GitOps Rules\n\n![CI](https://github.com/adobe/rules_gitops/workflows/CI/badge.svg?branch=master\u0026event=push)\n\nBazel 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.\n\nBazel GitOps Rules is an alternative to [rules_k8s](https://github.com/bazelbuild/rules_k8s). The main differences are:\n\n* Utilizes and integrates the full set of [Kustomize](https://kustomize.io/) capabilities for generating manifests.\n* Implements GitOps target.\n* Supports personal namespace deployments.\n* Provides integration test setup utility.\n* Speeds up deployments iterations:\n  * The results manifests are rendered without pushing containers.\n  * Pushes all the images in parallel.\n* Provides an utility that creates GitOps pull requests.\n\n\n## Rules\n\n* [k8s_deploy](#k8s_deploy)\n* [k8s_test_setup](#k8s_test_setup)\n\n\n## Guides\n\n* [Base Manifests and Overlays](#base-manifests-and-overlays)\n* [Generating Configmaps](#generating-configmaps)\n* [Injecting Docker Images](#injecting-docker-images)\n* [Adding Dependencies](#adding-dependencies)\n* [GitOps and Deployment](#gitops-and-deployment)\n* [Integration Testing Support](#integration-testing-support)\n\n\n\u003ca name=\"installation\"\u003e\u003c/a\u003e\n## Installation\n\nFrom the release you wish to use:\n\u003chttps://github.com/adobe/rules_gitops/releases\u003e\ncopy the WORKSPACE snippet into your `WORKSPACE` file.\n\n\n\u003ca name=\"k8s_deploy\"\u003e\u003c/a\u003e\n## k8s_deploy\n\nThe `k8s_deploy` creates rules that produce the `.apply` and `.gitops` targets `k8s_deploy` is defined in [k8s.bzl](./skylib/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\nthe appropriate location in the same os separate repository.\n\nFor example, let's look at the [example's k8s_deploy](./examples/helloworld/BUILD). We can peek at the file containing the rendered K8s manifests:\n```bash\ncd examples\nbazel run //helloworld:mynamespace.show\n```\nWhen 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.\n\n| Parameter                 | Default        | Description\n| ------------------------- | -------------- | -----------\n| ***cluster***             | `None`         | The name of the cluster in which these manifests will be applied.\n| ***namespace***           | `None`         | The target namespace to assign to all manifests. Any namespace value in the source manifests will be replaced or added if not specified.\n| ***user***                | `{BUILD_USER}` | The user passed to kubectl in .apply rule. Must exist in users ~/.kube/config\n| ***configmaps_srcs***     | `None`         | A list of files (of any type) that will be combined into configmaps. See [Generating Configmaps](#generating-configmaps).\n| ***configmaps_renaming*** | `None`         | Configmaps/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.\n| ***secrets_srcs***        | `None`         | A list of files (of any type) that will be combined into a secret similar to configmaps.\n| ***manifests***           | `glob(['*.yaml','*.yaml.tpl'])` | A list of base manifests. See [Base Manifests and Overlays](#base-manifests-and-overlays).\n| ***name_prefix***         | `None`         | Adds prefix to the names of all resources defined in manifests.\n| ***name_suffix***         | `None`         | Adds suffix to the names of all resources defined in manifests.\n| ***patches***             | `None`         | A list of patch files to overlay the base manifests. See [Base Manifests and Overlays](#base-manifests-and-overlays).\n| ***image_name_patches***  | `None`         | A dict of image names that will be replaced with new ones. See [kustomization images](https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/images/).\n| ***image_tag_patches***  | `None`         | A dict of image names which tags be replaced with new ones. See [kustomization images](https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/images/).\n| ***substitutions***       | `None`         | Does 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.\n| ***configurations***      | `[]`           | A list of files with [kustomize configurations](https://github.com/kubernetes-sigs/kustomize/blob/master/examples/transformerconfigs/README.md).\n| ***prefix_suffix_app_labels*** | `False`   | Add the bundled configuration file allowing adding suffix and prefix to labels `app` and `app.kubernetes.io/name` and respective selector in Deployment.\n| ***common_labels***       | `{}`           | A map of labels that should be added to all objects and object templates.\n| ***common_annotations***  | `{}`           | A map of annotations that should be added to all objects and object templates.\n| ***start_tag***           | `\"{{\"`         | The character start sequence used for substitutions.\n| ***end_tag***             | `\"}}\"`         | The character end sequence used for substitutions.\n| ***deps***                | `[]`           | A list of dependencies used to drive `k8s_deploy` functionality (i.e. `deps_aliases`).\n| ***deps_aliases***        | `{}`           | A dict of labels of file dependencies. File dependency contents are available for template expansion in manifests as `{{imports.\u003clabel\u003e}}`. Each dependency in this dictionary should be present in the `deps` attribute.\n| ***objects***             | `[]`           | A list of other instances of `k8s_deploy` that this one depends on. See [Adding Dependencies](#adding-dependencies).\n| ***images***              | `{}`           | A dict of labels of Docker images. See [Injecting Docker Images](#injecting-docker-images).\n| ***image_digest_tag***    | `False`        | A flag for whether or not to tag the image with the container digest.\n| ***image_registry***      | `docker.io`    | The registry to push images to.\n| ***image_repository***    | `None`         | The repository to push images to. By default, this is generated from the current package path.\n| ***image_repository_prefix*** | `None`     | Add a prefix to the image_repository. Can be used to upload the images in\n| ***image_pushes***        | `[]`           | A list of labels implementing K8sPushInfo referring image uploaded into registry. See [Injecting Docker Images](#injecting-docker-images).\n| ***release_branch_prefix*** | `master`     | A git branch name/prefix. Automatically run GitOps while building this branch. See [GitOps and Deployment](#gitops_and_deployment).\n| ***deployment_branch***   | `None`         | Automatic GitOps output will appear in a branch and PR with this name. See [GitOps and Deployment](#gitops_and_deployment).\n| ***gitops_path***         | `cloud`        | Path within the git repo where gitops files get generated into\n| ***tags***                | `[]`           | See [Bazel docs on tags](https://docs.bazel.build/versions/master/be/common-definitions.html#common-attributes).\n| ***visibility***          | [Default_visibility](https://docs.bazel.build/versions/master/be/functions.html#package.default_visibility) | Changes the visibility of all rules generated by this macro. See [Bazel docs on visibility](https://docs.bazel.build/versions/master/be/common-definitions.html#common-attributes).\n\n\n\u003ca name=\"base-manifests-and-overlays\"\u003e\u003c/a\u003e\n### Base Manifests and Overlays\n\nThe 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.\n\nThe 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**.\n\nTo demonstrate, let's go over hypothetical multi cluster deployment.\n\nHere is the fragment of the `k8s_deploy` rule that is responsible for generating manifest variants per CLOUD, CLUSTER, and NAMESPACE :\n```starlark\nk8s_deploy(\n    ...\n    manifests = glob([                 # (1)\n      \"manifests/*.yaml\",\n      \"manifests/%s/*.yaml\" % (CLOUD),\n    ]),\n    patches = glob([                   # (2)\n      \"overlays/*.yaml\",\n      \"overlays/%s/*.yaml\" % (CLOUD),\n      \"overlays/%s/%s/*.yaml\" % (CLOUD, NAMESPACE),\n      \"overlays/%s/%s/%s/*.yaml\" % (CLOUD, NAMESPACE, CLUSTER),\n    ]),\n    ...\n)\n```\nThe manifests list `(1)` combines common base manifests and `CLOUD` specific manifests.\n```\nmanifests\n├── aws\n│   └── pvc.yaml\n├── onprem\n│   ├── pv.yaml\n│   └── pvc.yaml\n├── deployment.yaml\n├── ingress.yaml\n└── service.yaml\n```\nHere we see that `aws` and `onprem` clouds have different persistence configurations `aws/pvc.yaml` and `onprem/pvc.yaml`.\n\nThe 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](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-api-machinery/strategic-merge-patch.md) update operation.\n```\noverlays\n├── aws\n│   ├── deployment.yaml\n│   ├── prod\n│   │   ├── deployment.yaml\n│   │   └── us-east-1\n│   │       └── deployment.yaml\n│   └── uat\n│       └── deployment.yaml\n└── onprem\n    ├── prod\n    │   ├── deployment.yaml\n    │   └── us-east\n    │       └── deployment.yaml\n    └── uat\n        └── deployment.yaml\n```\nThat looks like a lot. But lets try to decode what is happening here:\n\n1. `aws/deployment.yaml` adds persistent volume reference specific to all AWS deployments.\n1. `aws/prod/deployment.yaml` modifies main container CPU and memory requirements in production configurations.\n1. `aws/prod/us-east-1/deployment.yaml` adds monitoring sidecar.\n\n\n\u003ca name=\"generating-configmaps\"\u003e\u003c/a\u003e\n### Generating Configmaps\n\nConfigmaps 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:\n\n```starlark\n[\n    k8s_deploy(\n        name = NAME,\n        cluster = CLUSTER,\n        configmaps_srcs = glob([                 # (1)\n            \"configmaps/%s/**/*\" % CLUSTER\n        ]),\n        configmaps_renaming = 'hash',            # (2)\n\n        ...\n    )\n    for NAME, CLUSTER, NAMESPACE in [\n        (\"mynamespace\", \"dev\", \"{BUILD_USER}\"),  # (3)\n        (\"prod-grafana\", \"prod\", \"prod\"),        # (4)\n    ]\n]\n```\nHere we generate two `k8s_deploy` targets, one for `mynamespace` `(3)`, another for production deployment `(4)`.\n\nThe directory structure of `configmaps` looks like this:\n```\ngrafana\n└── configmaps\n    ├── dev\n    │   └── grafana\n    │       └── ldap.toml\n    └── prod\n        └── grafana\n            └── ldap.toml\n```\nThe `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:\n\n```yaml\napiVersion: v1\ndata:\n  ldap.toml: |\n    [[servers]]\n    ...\nkind: ConfigMap\nmetadata:\n  name: grafana-k75h878g4f\n  namespace: ops-prod\n```\nThe 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.\n\nIn 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:\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nspec:\n  template:\n    spec:\n      containers:\n      volumes:\n      ...\n      - configMap:\n          items:\n          - key: ldap.toml\n            path: ldap.toml\n          name: grafana-k75h878g4f\n        name: grafana-ldap\n```\n\n\n\u003ca name=\"injecting-docker-images\"\u003e\u003c/a\u003e\n### Injecting Docker Images\n\nThird-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](https://github.com/bazelbuild/rules_docker). For example, the `java_image` rule creates an image of a Java application from Java source code, dependencies, and configuration.\n\nHere's a (very contrived) example of how this ties in with `k8s_deploy`. Here's the `BUILD` file located in the package `//examples`:\n```starlark\njava_image(\n    name = \"helloworld_image\",\n    srcs = glob([\"*.java\"]),\n    ...\n)\nk8s_deploy(\n    name = \"helloworld\",\n    manifests = [\"helloworld.yaml\"],\n    images = {\n        \"helloworld_image\": \":helloworld_image\",  # (1)\n    }\n)\n```\nAnd here's `helloworld.yaml`:\n```yaml\napiVersion: v1\nkind: Pod\nmetadata:\n  name: helloworld\nspec:\n  containers:\n    - image: //examples:helloworld_image  # (2)\n```\nThere `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)`.\n\nThe `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](https://docs.bazel.build/versions/master/skylark/lib/Label.html#name) of the image target.\n\nWhen we `bazel build` the example, the rendered manifest will look something like this:\n```yaml\napiVersion: v1\nkind: Pod\nmetadata:\n  name: helloworld\nspec:\n  containers:\n    - image: registry.example.com/examples/helloworld_image@sha256:c94d75d68f4c1b436f545729bbce82774fda07\n```\n\nThe 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`:\n```yaml\napiVersion: v1\nkind: Pod\nmetadata:\n  name: helloworld\nspec:\n  containers:\n    - image: helloworld_image\n```\n\nImage substitutions for Custom Resource Definitions (CRD) resources could also use target references directly. Their digests are available through string substitution. For example,\n```yaml\napiVersion: v1\nkind: MyCrd\nmetadata:\n  name: my_crd\n  labels:\n    app_label_image_digest: \"{{//examples:helloworld_image.digest}}\"\n    app_label_image_short_digest: \"{{//examples:helloworld_image.short-digest}}\"\nspec:\n  image: \"{{//examples:helloworld_image}}\"\n```\nwould become\n```yaml\napiVersion: v1\nkind: MyCrd\nmetadata:\n  name: my_crd\n  labels:\n    app_label_image_digest: \"e6d465223da74519ba3e2b38179d1268b71a72f\"\n    app_label_image_short_digest: \"e6d465223d\"\nspec:\n  image: registry.example.com/examples/helloworld_image@sha256:e6d465223da74519ba3e2b38179d1268b71a72f\n```\n\nAn 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 [helloworld](examples/helloworld/deployment.yaml) for a complete example.\n\nAs with the rest of the dependency graph, Bazel understands the dependencies `k8s_deploy` has on the\nDocker image and the files in the image. So for example, here's what will happen if someone makes a change to one of the Java files in `helloworld_image` and then runs `bazel run //examples:helloworld.apply`:\n1. The `helloworld_image` will be rebuilt with the new code and uploaded to the registry\n1. A new `helloworld` manifest will be rendered using the new image\n1. The new `helloworld` pod will be deployed\n\nIt is possible to use alternative ways to resolve images as long as respective rule implements K8sPushInfo provider. For example, this setup will mirror the referred image into a local registry and provide a reference to it. `k8s_deploy` will need to use `image_pushes` parameter:\n\n```starlark\nload(\"@com_fasterci_rules_mirror//mirror:defs.bzl\", \"mirror_image\")\nmirror_image(\n    name = \"agnhost_image\",\n    digest = \"sha256:93c166faf53dba3c9c4227e2663ec1247e2a9a193d7b59eddd15244a3e331c3e\",\n    dst_prefix = \"gcr.io/myregistry/mirror\",\n    src_image = \"registry.k8s.io/e2e-test-images/agnhost:2.39\",\n)\nk8s_deploy(\n    name = \"agnhost\",\n    manifests = [\"agnhost.yaml\"],\n    image_pushes = [\n        \":agnhost_image\",\n    ]\n)\n```\n\n\n\u003ca name=\"adding-dependencies\"\u003e\u003c/a\u003e\n### Adding Dependencies\n\nMany instances of `k8s_deploy` include an `objects` attribute that references other instances of\n`k8s_deploy`. When chained this way, running the `.apply` will also apply any dependencies as well.\n\nFor example, to add dependency to the example [helloworld deployment](./examples/helloworld/BUILD):\n```starlark\nk8s_deploy(\n    name = \"mynamespace\",\n    objects = [\n        \"//other:mynamespace\",\n    ],\n    ...\n)\n```\nWhen you run `bazel run //helloworld:mynamespace.apply`, it'll deploy a _helloword_ and _other_  service instance into your namespace.\n\nPlease note that the `objects` attribute is ignored by `.gitops` targets.\n\n\n\u003ca name=\"gitops-and-deployment\"\u003e\u003c/a\u003e\n## GitOps and Deployment\n\nThe simplified CI pipeline that incorporates GitOps will look like this:\n```\n[Checkout Code] -\u003e [Bazel Build \u0026 Test] -\u003e (if GitOps source branch) -\u003e [Create GitOps PRs]\n```\n\nThe *Create GitOps PRs* step usually is the last step of a CI pipeline. `rules_gitops` provides the `create_gitops_prs` command line tool that automates the process of creating pull requests.\n\nFor the full list of `create_gitops_prs` command line options, run:\n```bash\nbazel run @com_adobe_rules_gitops//gitops/prer:create_gitops_prs\n```\n\n\u003ca name=\"gitops-and-deployment-supported-git-servers\"\u003e\u003c/a\u003e\n### Supported Git Servers\n\nThe `--git_server` parameter defines the type of a Git server API to use. The supported Git server types are `github`, `gitlab`, and `bitbucket`.\n\nDepending on the Git server type the `create_gitops_prs` tool will use following command line parameters:\n\n--git_server | Parameter                            | Default\n------------ | ------------------------------------ | --------------\n| `github`\n|            | ***--github_repo_owner***            | ``\n|            | ***--github_repo***                  | ``\n|            | ***--github_access_token***          | `$GITHUB_TOKEN`\n|            | ***--github_enterprise_host***       | ``\n| `gitlab`   |\n|            | ***--gitlab_host***                  | `https://gitlab.com`\n|            | ***--gitlab_repo***                  | ``\n|            | ***--gitlab_access_token***          | `$GITLAB_TOKEN`\n| `bitbucket`\n|            | ***--bitbucket_api_pr_endpoint***    | ``\n|            | ***--bitbucket_user***               | `$BITBUCKET_USER`\n|            | ***--bitbucket_password***           | `$BITBUCKET_PASSWORD`\n\n\u003ca name=\"trunk-based-gitops-workflow\"\u003e\u003c/a\u003e\n## Trunk Based GitOps Workflow\n\nFor example let's assume the CI build pipeline described above is running the build for `https://github.com/example/repo.git`. We are using trunk based branching model. All feature branches are merged into the `master` branch first. The *Create GitOps PRs* step runs on a `master` branch change. The GitOps deployments source files are located in the same repository under the `/cloud` directory.\n\nThe *Create GitOps PRs* pipeline step shell command will look like following:\n```bash\nGIT_ROOT_DIR=$(git rev-parse --show-toplevel)\nGIT_COMMIT_ID=$(git rev-parse HEAD)\nGIT_BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\nif [ \"${GIT_BRANCH_NAME}\" == \"master\"]; then\n    bazel run @com_adobe_rules_gitops//gitops/prer:create_gitops_prs -- \\\n        --workspace $GIT_ROOT_DIR \\\n        --git_repo https://github.com/example/repo.git \\\n        --git_mirror $GIT_ROOT_DIR/.git \\\n        --git_server github \\\n        --release_branch master \\\n        --gitops_pr_into master \\\n        --gitops_pr_title \"This is my pull request title\" \\\n        --gitops_pr_body \"This is my pull request body message\" \\\n        --branch_name ${GIT_BRANCH_NAME} \\\n        --git_commit ${GIT_COMMIT_ID} \\\nfi\n```\n\nThe `GIT_*` variables describe the current state of the Git repository.\n\nThe `--git_repo` parameter defines the remote repository URL. In this case remote repository matches the repository of the working copy. The `--git_mirror` parameter is an optimization used to speed up the target repository clone process using reference repository (see `git clone --reference`). The `--git-server` parameter selects the type of Git server.\n\nThe `--release_branch` specifies the value of the ***release_branch_prefix*** attribute of `gitops` targets (see [k8s_deploy](#k8s_deploy)). The `--gitops_pr_into` defines the target branch for newly created pull requests. The `--branch_name` and `--git_commit` are the values used in the pull request commit message.\n\nThe `create_gitops_prs` tool will query all `gitops` targets which have set the ***deploy_branch*** attribute (see [k8s_deploy](#k8s_deploy)) and the ***release_branch_prefix*** attribute value that matches the `release_branch` parameter.\n\nThe all discovered `gitops` targets are grouped by the value of ***deploy_branch*** attribute. The one deployment branch will accumulate the output of all corresponding `gitops` targets.\n\nFor example, we define two deployments: grafana and prometheus. Both deployments share the same namespace. The deployments a grouped by namespace.\n```starlark\n[\n    k8s_deploy(\n        name = NAME,\n        deploy_branch = NAMESPACE,\n        ...\n    )\n    for NAME, CLUSTER, NAMESPACE in [\n        ...\n        (\"stage-grafana\", \"stage\", \"monitoring-stage\"),\n        (\"prod-grafana\", \"prod\", \"monitoring-prod\"),\n    ]\n]\n[\n    k8s_deploy(\n        name = NAME,\n        deploy_branch = NAMESPACE,\n        ...\n    )\n    for NAME, CLUSTER, NAMESPACE in [\n        ...\n        (\"stage-prometheus\", \"stage\", \"monitoring-stage\"),\n        (\"prod-prometheus\", \"prod\", \"monitoring-prod\"),\n    ]\n]\n```\n\nAs a result of the setup above the `create_gitops_prs` tool will open up to 2 potential deployment pull requests:\n* from `deploy/monitoring-stage` to `master` including manifests for `stage-grafana` and `stage-prometheus`\n* from `deploy/monitoring-prod` to `master` including manifests for `prod-grafana` and `prod-prometheus`\n\nThe GitOps pull request is only created (or new commits added) if the `gitops` target changes the state for the target deployment branch. The source pull request will remain open (and keep accumulation GitOps results) until the pull request is merged and source branch is deleted.\n\nThe `--stamp` parameter allows for the replacement of certain placeholders, but only when the `gitops` target changes the output's digest compared to the one already saved. The new digest of the unstamped data is also saved with the manifest. The digest is kept in a file in the same location as the YAML file, with a `.digest` extension added to its name. This is helpful when the manifests have volatile information that shouldn't be the only factor causing changes in the target deployment branch.\n\nHere are the placeholders that can be replaced:\n\n| Placeholder      | Replacement                                    |\n|------------------|-------------------------------------------------|\n| `{{GIT_REVISION}}` | Result of `git rev-parse HEAD`                  |\n| `{{UTC_DATE}}`     | Result of `date -u`                             |\n| `{{GIT_BRANCH}}`   | The `branch_name` argument given to `create_gitops_prs` |\n\n`--dry_run` parameter can be used to test the tool without creating any pull requests. The tool will print the list of the potential pull requests. It is recommended to run the tool in the dry run mode as a part of the CI test suite to verify that the tool is configured correctly.\n\n\u003ca name=\"multiple-release-branches-gitops-workflow\"\u003e\u003c/a\u003e\n## Multiple Release Branches GitOps Workflow\n\nIn the situation when the trunk based branching model in not suitable the `create_gitops_prs` tool supports creating GitOps pull requests before the code is merged to `master` branch.\n\nBoth trunk and release branch workflow could coexists in the same repository.\n\nFor example, let's assume the CI build pipeline described above is running the build for `https://github.com/example/repo.git`. We are using release branch branching model. Feature request are merged into multiple target release branches. The release brach name convention is `release/team-\u003cYYYYMMDD\u003e`. The *Create GitOps PRs* step is running on the release branch change. GitOps deployments source files are located in the same repository `/cloud` directory in the `master` branch.\n\nThe *Create GitOps PRs* pipeline step shell command will look like following:\n```bash\nGIT_ROOT_DIR=$(git rev-parse --show-toplevel)\nGIT_COMMIT_ID=$(git rev-parse HEAD)\nGIT_BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)          # =\u003e release/team-20200101\nRELEASE_BRANCH_SUFFIX=${GIT_BRANCH_NAME#\"release/team\"}     # =\u003e -20200101\nRELEASE_BRANCH=${GIT_BRANCH_NAME%${RELEASE_BRANCH_SUFFIX}}  # =\u003e release/team\nif [ \"${RELEASE_BRANCH}\" == \"release/team\"]; then\n    bazel run @com_adobe_rules_gitops//gitops/prer:create_gitops_prs -- \\\n        --workspace $GIT_ROOT_DIR \\\n        --git_repo https://github.com/example/repo.git \\\n        --git_mirror $GIT_ROOT_DIR/.git \\\n        --git_server github \\\n        --release_branch ${RELEASE_BRANCH} \\\n        --deployment_branch_suffix=${RELEASE_BRANCH_SUFFIX} \\\n        --gitops_pr_into master \\\n        --gitops_pr_title \"This is my pull request title\" \\\n        --gitops_pr_body \"This is my pull request body message\" \\\n        --branch_name ${GIT_BRANCH_NAME} \\\n        --git_commit ${GIT_COMMIT_ID} \\\nfi\n```\n\nThe meaning of the parameters is the same as with [trunk based workflow](#trunk_based_gitops_workflow).\nThe `--release_branch` parameter takes the value of `release/team`. The additional parameter `--deployment_branch_suffix` will add the release branch suffix to the target deployment branch name.\n\nIf we modify previous example:\n```starlark\n[\n    k8s_deploy(\n        name = NAME,\n        deploy_branch = NAMESPACE,\n        release_branch_prefix = \"release/team\",  # will be selected only when --release_branch=release/team\n        ...\n    )\n    for NAME, CLUSTER, NAMESPACE in [\n        ...\n        (\"stage-grafana\", \"stage\", \"monitoring-stage\"),\n        (\"prod-grafana\", \"prod\", \"monitoring-prod\"),\n    ]\n]\n[\n    k8s_deploy(\n        name = NAME,\n        deploy_branch = NAMESPACE,\n        release_branch_prefix = \"release/team\",  # will be selected only when --release_branch=release/team\n        ...\n    )\n    for NAME, CLUSTER, NAMESPACE in [\n        ...\n        (\"stage-prometheus\", \"stage\", \"monitoring-stage\"),\n        (\"prod-prometheus\", \"prod\", \"monitoring-prod\"),\n    ]\n]\n```\n\nThe result of the setup above the `create_gitops_prs` tool will open up to 2 potential deployment pull requests per release branch. Assuming release branch name is `release/team-20200101`:\n* from `deploy/monitoring-stage-20200101` to `master` including manifests for `stage-grafana` and `stage-prometheus`\n* from `deploy/monitoring-prod-20200101` to `master` including manifests for `prod-grafana` and `prod-prometheus`\n\n\n\u003ca name=\"integration-testing-support\"\u003e\u003c/a\u003e\n## Integration Testing Support\n\n**Note:** the Integration testing support has known limitations and should be considered **experimental**. The public API is subject to change.\n\nIntegration tests are defined in `BUILD` files like this:\n```starlark\nk8s_test_setup(\n    name = \"service_it.setup\",\n    kubeconfig = \"@k8s_test//:kubeconfig\",\n    objects = [\n        \"//service:mynamespace\",\n    ],\n)\n\njava_test(\n    name = \"service_it\",\n    srcs = [\n        \"ServiceIT.java\",\n    ],\n    data = [\n        \":service_it.setup\",\n    ],\n    jvm_flags = [\n        \"-Dk8s.setup=$(location :service_it.setup)\",\n    ],\n    # other attributes omitted for brevity\n)\n```\nThe test is composed of two rules, a `k8s_test_setup` rule to manage the Kubernetes setup and a `java_test` rule that executes the actual test.\n\nThe `k8s_test_setup` rule produces a shell script which creates a temporary namespace (the namespace name is your username followed by five random digits) and creates a kubeconfig file that allows access to this new namespace. Inside the namespace, it creates some objects specified in the `objects` attributes. In the example, there is one target here: `//service:mynamespace`. This target represents a file containing all the Kubernetes object manifests required to run the service.\n\nThe output of the `k8s_test_setup` rule (a shell script) is referenced in the `java_test` rule. It's listed under the `data` attribute, which declares the target as a dependency, and is included in the jvm flags in this clause: `$(location :service_it.setup)`. The \"location\" function is specific to Bazel: given a target, it returns the path to the file produced by that target. In this case, it returns the path to the shell script created by our `k8s_test_setup` rule.\n\nThe test code launches the script to perform the test setup. The test code should also monitor the script console output to listen to the pod readiness events.\n\nThe `@k8s_test//:kubeconfig` target referenced from `k8s_test_setup` rule serves the purpose of making Kubernetes configuration available in the test sandbox. The `kubeconfig` repository rule in the `WORKSPACE` file will need, at minimum, provide the cluster name.\n\n```starlark\nload(\"@com_adobe_rules_gitops//gitops:defs.bzl\", \"kubeconfig\")\n\nkubeconfig(\n    name = \"k8s_test\",\n    cluster = \"dev\",\n)\n```\n\n\u003ca name=\"k8s_test_setup\"\u003e\u003c/a\u003e\n### k8s_test_setup\n\n**Note:** the `k8s_test_setup` rule is an **experimental** feature and is subject to change.\n\nAn executable that performs Kubernetes test setup:\n\n- creates temporary namespace\n- creates kubectl configuration with the default context set to the created namespace\n- deploys all dependent ***objects***\n- forwards service ports\n\n| Parameter                  | Default        | Description\n| -------------------------- | -------------- | -----------\n| ***kubeconfig***           | `@k8s_test//:kubeconfig` | The Kubernetes configuration file target.\n| ***kubectl***              | `@k8s_test//:kubectl` | The Kubectl executable target.\n| ***objects***              | `None` | A list of other instances of `k8s_deploy` that test depends on. See [Adding Dependencies](#adding-dependencies)\n| ***setup_timeout***        | `10m`  | The time to wait until all required services become ready. The timeout duration should be lower that Bazel test timeout.\n| ***portforward_services*** | `None` | The list of Kubernetes service names to port forward. The setup will wait for at least one service endpoint to become ready.\n\n\u003ca name=\"kubeconfig\"\u003e\u003c/a\u003e\n### kubeconfig\n\n**Note:** the `kubeconfig` repository rule is an **experimental** feature and is subject to change.\n\nConfigures Kubernetes tools for testing.\n\n| Parameter                 | Default        | Description\n| ------------------------- | -------------- | -----------\n| ***cluster***             | `None`         | The Kubernetes cluster name as defined in the host `kubectl` configuration.\n| ***server***              | `None`         | Optional Kubernetes server endpoint to override automatically detected server endpoint. By default, the server endpoint is automatically detected based on the environment. When running inside the Kubernetes cluster (the service account is present), the server endpoint is derived from `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` environment variables. If environment variable are nto defined the server name is set to `https://kubernetes.default`. Otherwise the host `kubectl` configuration file is used.\n| ***user***                | `None` | Optional Kubernetes configuration user name. Default value is the current build user.\n\n## Building \u0026 Testing\n\n### Building \u0026 Testing GitOps Rules\n\n```bash\nbazel test //...\n```\n\n### Building \u0026 Testing Examples Project\n\n```bash\ncd examples\nbazel test //...\n```\n\n## Have a Question\n\nFind the `rules_gitops` contributors in the [#gitops](https://bazelbuild.slack.com/archives/C01SF68MTFS) channel on the [Bazel Slack](https://slack.bazel.build/).\n\n\n## Contributing\n\nContributions are welcomed! Read the [Contributing Guide](./.github/CONTRIBUTING.md) for more information.\n\n\n## Adopters\nHere's a (non-exhaustive) list of companies that use `rules_gitops` in production. Don't see yours? [You can add it in a PR!](https://github.com/adobe/rules_gitops/edit/master/README.md)\n  * [Adobe (Advertising Cloud)](https://www.adobe.com/advertising/adobe-advertising-cloud.html)\n  * [FasterCI](https://fasterci.com)\n  * [Skydio](https://www.skydio.com)\n\n## Licensing\n\nThe contents of third party dependencies in [/vendor](./vendor) folder are covered by their repositories' respective licenses.\n\nThe contents of [/templating/fasttemplate](./templating/fasttemplate) are licensed under MIT License. See [LICENSE](./templating/fasttemplate/LICENSE) for more information.\n\nAll other files are licensed under the Apache V2 License. See [LICENSE](LICENSE) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fadobe%2Frules_gitops","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fadobe%2Frules_gitops","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fadobe%2Frules_gitops/lists"}