DEV Community

Cover image for Grafana GitSync on Azure DevOps
Boluwatife Morawo
Boluwatife Morawo

Posted on Originally published at codejourney.io

Grafana GitSync on Azure DevOps

Grafana's Git Sync features let you sync your dashboards as JSON/YAML files in Git and manage them as code. This brings the auditability and automation goodies of Git with the added benefit of bi-directional synchronization.

You also get enhanced integration features like automated pull request comments with dashboard preview for specific Git providers such as GitHub, GitLab and Bitbucket.

Any provider that's not directly supported is meant to use pure git which offers Git over HTTPS with no provider-specific logic. Seeing as there is no specific support for Azure DevOps, pure git seems like the obvious way out until you realize that pure git only supports Smart HTTP protocol v2 while Azure DevOps only uses v1.

Fear not though, we will explore a neat solution to this dilemma.

TL;DR

The 2 pieces of the puzzle are git-v2-azuredevops-proxy and Grafana Git Sync PR Preview. If you're using Kubernetes, these are the steps summarized.

  1. Install the proxy with Helm next to Grafana, pointing it at your Azure DevOps repository.
  2. Whitelist the proxy's in-cluster address in Grafana, and configure a pure git repository in Grafana that points at this address.
  3. Install the PR Preview extension in Azure DevOps, and add its task to a pipeline that runs as build validation on your pull requests.

Azure DevOps Proxy

Azure DevOps Proxy (git-v2-azuredevops-proxy) is a Smart HTTP server that translates protocol v1 into protocol v2 on behalf of Azure DevOps. It's the exact solution that Grafana needs for Git Sync to work. Let's explore how to set it up.

๐Ÿ’ก The examples in this post use Kubernetes but can also be implemented with docker-compose or just docker.

Requirements

  • A Kubernetes cluster.
  • An Azure DevOps personal access token with Code (Read & Write) on the repository. Authentication can be done via Entra workload identity or client ID/secret, but I chose a PAT for simplicity in this guide.

Great to have

  • A Gateway API implementation, for Grafana's public hostname.
  • cert-manager with API access to your domain's DNS, or any other way to get a trusted TLS certificate for Grafana's hostname. In this post, I used Hetzner to manage the domain.
  • Crossplane if you want to manage Grafana with Infrastructure as Code (IaC).

Step 0: Routing and Certificate for Grafana

Follow through with this section if you have a domain and want to set up your Grafana instance to be accessible over HTTPS; otherwise, skip to step 1.

Envoy Gateway

Install the Envoy Gateway chart (or any gateway implementation of your choice).

# this chart also comes with the gateway api crd
# but you probably want to manage that separately.
helm install envoy-gateway oci://docker.io/envoyproxy/gateway-helm \
  --version v1.10.0 -n envoy-gateway-system --create-namespace --wait
Enter fullscreen mode Exit fullscreen mode

Create the GatewayClass that Gateways use to pick Envoy Gateway:

# gatewayclass.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: envoy
spec:
  controllerName: gateway.envoyproxy.io/gatewayclass-controller
Enter fullscreen mode Exit fullscreen mode
kubectl apply -f gatewayclass.yaml
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก On k3s, the bundled Traefik already takes ports 80 and 443. Install k3s with --disable=traefik so that those ports are free for Envoy Gateway's LoadBalancer to use.

Cert Manager

Install cert-manager

helm repo add jetstack https://charts.jetstack.io
helm upgrade --install cert-manager jetstack/cert-manager \
  -n cert-manager --create-namespace --set crds.enabled=true --wait
Enter fullscreen mode Exit fullscreen mode

Install the cluster issuer

The cluster issuer enables the issuing of signed TLS certificates across all namespaces in a cluster.
This example uses Hetzner's cert-manager webhook. cert-manager also supports many default providers and webhook providers.

Create a read & write API token in the Hetzner Console (your project > Security > API tokens). A ClusterIssuer reads its Secrets from the cert-manager namespace, so store the token there, then install the webhook:

# secret and webhook
kubectl -n cert-manager create secret generic hetzner --from-literal=token='<your Hetzner API token>'

helm repo add hcloud https://charts.hetzner.cloud
helm install cert-manager-webhook-hetzner hcloud/cert-manager-webhook-hetzner --version 0.9.1 -n cert-manager --wait
Enter fullscreen mode Exit fullscreen mode
# cluster-issuer.yaml
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      # cert-manager creates this Secret itself and keeps your Let's Encrypt account key in it.
      # There is nothing to create here.
      name: letsencrypt-account
    solvers:
      - dns01:
          webhook:
            groupName: acme.hetzner.com
            solverName: hetzner
            config:
              tokenSecretKeyRef:   # the Secret created above
                name: hetzner
                key: token
Enter fullscreen mode Exit fullscreen mode
kubectl apply -f cluster-issuer.yaml
Enter fullscreen mode Exit fullscreen mode

Install Gateway & Certificate

# gateway.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: public
  namespace: envoy-gateway-system
spec:
  gatewayClassName: envoy   # Envoy Gateway; use your own GatewayClass
  listeners:
    - name: https
      protocol: HTTPS
      port: 443
      hostname: "*.example.com"
      tls:
        certificateRefs:
          - name: public-tls   # the Certificate below, in the same namespace
      allowedRoutes:
        namespaces:
          from: All   # allow all namespaces including grafana to use this gateway
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: public-tls
  namespace: envoy-gateway-system
spec:
  secretName: public-tls
  issuerRef:
    kind: ClusterIssuer
    name: letsencrypt
  dnsNames:
    - "*.example.com"   # covers grafana.example.com and any later hostname
Enter fullscreen mode Exit fullscreen mode
kubectl apply -f gateway.yaml

# check Envoy Gateway readiness
kubectl -n envoy-gateway-system wait gateway/public --for=condition=Programmed --timeout=5m
# check certificate readiness; the DNS-01 check can take a few minutes
kubectl -n envoy-gateway-system wait certificate/public-tls --for=condition=Ready --timeout=10m
Enter fullscreen mode Exit fullscreen mode

Step 1: Create the repository

Git Sync needs a repository with at least one commit on the branch it syncs. The folder for the dashboards doesn't need to exist yet: Grafana creates it when you save your first dashboard in step 5.

In Azure DevOps, open your project and go to Repos. Open the repository list at the top of the page and select New repository. Fill in:

Field Value
Repository type Git
Repository name dashboards
Add a README ticked, so that main has its first commit

Then select Create.

Or with the Azure CLI

az repos create creates an empty repository, so push a first commit yourself:

az repos create --org https://dev.azure.com/contoso --project Monitoring --name dashboards

git clone https://dev.azure.com/contoso/Monitoring/_git/dashboards
cd dashboards
git switch -c main
echo "# dashboards" > README.md
git add README.md
git commit -m "Add README"
git push -u origin main
Enter fullscreen mode Exit fullscreen mode

Step 2: Install the proxy

Create a PAT with the Custom defined scope Code > Read & write.

Store the PAT in a Secret and reference it in the Helm chart.

kubectl create namespace grafana

kubectl -n grafana create secret generic azure-devops-pat --from-literal=AZURE_PAT='<your PAT>'
Enter fullscreen mode Exit fullscreen mode
# git-proxy-helm-values.yaml
repos:
  # limit it to the specific dashboard repos
  - https://dev.azure.com/contoso/Monitoring/_git/dashboards # use your own repos

upstream:
  auth: pat
  pat:
    existingSecret: azure-devops-pat   # key AZURE_PAT

# Skipping proxyAuth because the network policy below is safe enough.
proxyAuth: none

syncInterval: 30   # seconds between fetches from Azure DevOps

persistence:
  size: 5Gi   # the mirrors of your repositories live here

networkPolicy:
  # by default, only admits pods labelled app.kubernetes.io/name: grafana
  enabled: true
Enter fullscreen mode Exit fullscreen mode
helm install git-proxy oci://ghcr.io/dominik-esb/charts/git-v2-azuredevops-proxy \
  --version 2.2.0 -n grafana -f git-proxy-helm-values.yaml --wait
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก In production, you should probably use Microsoft Entra workload identity (upstream.auth: entraWorkloadIdentity) or client id/secrets (entraClientSecret). See the chart's README.

Step 3: Install Grafana

Create the Grafana admin secret and reference it in the Helm chart. Git Sync is on by default in Grafana 13.

# Added a `credentials` key, so that Crossplane can authenticate. See Step 3.1
PASSWORD='<a strong password>'
kubectl -n grafana create secret generic grafana-admin \
  --from-literal=admin-user=admin \
  --from-literal=admin-password="$PASSWORD" \
  --from-literal=credentials="{\"auth\": \"admin:$PASSWORD\"}"
Enter fullscreen mode Exit fullscreen mode
# grafana-helm-values.yaml
admin:
  # the Secret has the keys admin-user and admin-password, as created above
  existingSecret: grafana-admin

# only needed to enable URL access to Grafana itself
route:
  main:
    enabled: true
    parentRefs:
      - name: public
        namespace: envoy-gateway-system
        sectionName: https
    hostnames:
      - grafana.example.com

grafana.ini:
  server:
    root_url: https://grafana.example.com
  provisioning:
    # allow the proxy's service url over http://
    allowed_git_urls: git-proxy-git-v2-azuredevops-proxy.grafana.svc.cluster.local
    allow_insecure: true

persistence:
  enabled: true
  size: 5Gi
Enter fullscreen mode Exit fullscreen mode
helm repo add grafana-community https://grafana-community.github.io/helm-charts
helm install grafana grafana-community/grafana --version 14.5.0 -n grafana -f grafana-helm-values.yaml --wait
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”’ With allow_insecure, Git traffic between Grafana and the proxy crosses the pod network unencrypted. It's good practice to run a container network interface (CNI) that encrypts traffic between pods, such as Cilium, Calico with WireGuard, or a service mesh with mTLS. Then nothing in the cluster travels in cleartext. If you'd rather keep allow_insecure off, the bonus section at the end shows how to give the proxy its own HTTPS certificate.

Step 3.1: Install Crossplane for IaC

If you want to manage Grafana as code, then install Crossplane and set up the Grafana provider.

helm repo add crossplane-stable https://charts.crossplane.io/stable
helm install crossplane crossplane-stable/crossplane --version 2.5.0 -n crossplane-system --create-namespace --wait
Enter fullscreen mode Exit fullscreen mode
# provider.yaml
apiVersion: pkg.crossplane.io/v1
kind: Provider
metadata:
  name: provider-grafana
spec:
  package: xpkg.upbound.io/grafana/provider-grafana:v2.18.1
Enter fullscreen mode Exit fullscreen mode
kubectl apply -f provider.yaml
kubectl wait provider.pkg.crossplane.io/provider-grafana --for=condition=Healthy --timeout=10m
Enter fullscreen mode Exit fullscreen mode

After the provider is ready, configure it to connect to Grafana.

# providerconfig.yaml
apiVersion: grafana.m.crossplane.io/v1beta1
kind: ProviderConfig
metadata:
  name: grafana
  namespace: grafana
spec:
  url: http://grafana.grafana.svc
  credentials:
    source: Secret
    secretRef:
      name: grafana-admin
      namespace: grafana
      # `credentials` key of the `grafana-admin` Secret from step 3:
      key: credentials
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก The credentials key also accepts a service account token instead of user:password. You can create the service account from the Grafana UI under Administration > Users and access > Service accounts with the Admin role, create/copy a token, and use {"auth": "<token>"} as the credentials secret value instead.


Step 4: Connect Git Sync to the Azure DevOps proxy

In Grafana, go to Administration > Provisioning, configure Git Sync with the Pure Git type, and fill in:

Field Value
Repository URL http://git-proxy-git-v2-azuredevops-proxy.grafana.svc.cluster.local/dashboards.git
Branch main
Path dashboards/
Username git. Required field but ignored in this example (proxyAuth: none).
Token unused. Required field but ignored in this example (proxyAuth: none).

As IaC

You can place this file in the same repo created earlier.

# grafana/repositories/dashboards.yaml
apiVersion: oss.grafana.m.crossplane.io/v1alpha1
kind: RepositoryV0Alpha1
metadata:
  name: dashboards
  namespace: grafana
spec:
  providerConfigRef:
    kind: ProviderConfig
    name: grafana
  forProvider:
    metadata:
      uid: dashboards   # the repository's name in Grafana
    spec:
      title: Dashboards
      type: git
      git:
        url: http://git-proxy-git-v2-azuredevops-proxy.grafana.svc.cluster.local/dashboards.git
        branch: main
        path: dashboards/
        tokenUser: git # Required field but ignored in this example (proxyAuth: none)
      sync:
        enabled: true
        target: folder
        intervalSeconds: 60
      workflows: [write, branch]   # save to main, or to a new branch for a pull request
    secure:
      token:
        create: unused # Required field but ignored in this example (proxyAuth: none)
    secureVersion: 1
Enter fullscreen mode Exit fullscreen mode
kubectl apply -f providerconfig.yaml -f grafana/repositories/dashboards.yaml
# Check that SYNCED and READY are True.
kubectl -n grafana get repositoryv0alpha1.oss.grafana.m.crossplane.io
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก You can also skip Crossplane and apply the repository straight to Grafana. It's a Grafana resource of its own, kind: Repository with apiVersion: provisioning.grafana.app/v0alpha1, with the same spec and secure fields as forProvider above. Push the manifest with gcx (gcx resources push --path <folder>). Grafana's Git Sync as code guide has a full example for a GitHub repository.


Within a minute the repository should turn healthy, and a Dashboards folder for it shows up under Dashboards. It's empty, because the repository has no dashboards yet.

Step 5: Save your first dashboard to the repository

Open the Dashboards folder, select Create dashboard and create the dashboard as you please:

The empty Dashboards folder that Git Sync created, with a Create dashboard button.

In this example, we use Grafana's built-in TestData data source.

The panel editor with a Time series panel titled Requests per second, drawing data from the TestData data source.

Select Save. The folder belongs to the repository, so the save drawer will ask where to put the file in Git:

Field Value
Title Service health
Branch main. Type a new branch name instead to save to a branch for a pull request.
Repository folder platform. A folder inside dashboards/; Grafana creates it.
Filename service-health.yaml. Use .json if you prefer JSON.
Comment Add the Service health dashboard. This is the commit message.

The Save dashboard drawer with the title Service health, branch main, repository folder platform, filename service-health.yaml and a commit comment.

Select Save. Grafana commits the dashboard through the proxy with your Grafana user as the author. In this example, Grafana also commits dashboards/platform/_folder.json, which holds the platform folder's name and ID.

The saved Service health dashboard with its Requests per second and Error rate panels, inside the platform folder of the Dashboards folder.

From now on, it works both ways: edit the dashboard in Grafana and save it for a new commit, or change the file in Azure DevOps and Git Sync updates the dashboard in Grafana.

โฑ Changes pushed to Azure DevOps reach Grafana after up to syncInterval (the proxy) plus intervalSeconds (Git Sync).

Implementing Grafana Git Sync PR Preview

Grafana Git Sync PR Preview is an Azure Pipelines extension that brings the "pull request comments with dashboard preview" feature into Azure DevOps. A preview link opens the Grafana preview page that matches the pull request branch.

Step 1: Install the extension

Install Grafana Git Sync PR Preview in your Azure DevOps organization.

Give the project's build service "Contribute to pull requests" permission on the repository:

Project settings > Repositories > dashboards > Security > <project> Build Service.

This is the only permission the task needs.

Step 2: Add the pipeline

In the Azure DevOps repo, add an Azure Pipelines file with the GrafanaGitSyncPreview task:

# azure-pipelines.yml
trigger: none

pool:
  vmImage: ubuntu-latest

steps:
  - checkout: self
    fetchDepth: 2   # the task diffs HEAD against HEAD^1, the target branch

  - task: GrafanaGitSyncPreview@1
    inputs:
      grafanaUrl: https://grafana.example.com
      repositorySource: inline
      # <folder path in this repo>=<Git Sync repository name in Grafana>, one per line
      repositories: |
        dashboards=dashboards
Enter fullscreen mode Exit fullscreen mode

The repo's structure should now look like this:

dashboards/
  platform/_folder.json
  platform/service-health.yaml
azure-pipelines.yml # we just added this
Enter fullscreen mode Exit fullscreen mode

Or read the Crossplane repository file

If you went with the As IaC option (RepositoryV0Alpha1.oss.grafana.m.crossplane.io or Repository.provisioning.grafana.app) in step 4, the task can read the mapping directly from it using the repositoriesFile key:

  - task: GrafanaGitSyncPreview@1
    inputs:
      grafanaUrl: https://grafana.example.com
      repositoriesFile: grafana/repositories/*.yaml
Enter fullscreen mode Exit fullscreen mode

It takes the folder from spec.git.path, the Grafana repository name from metadata.uid, and the synced branch from spec.git.branch. This approach is more aligned with the single source of truth pattern.


In Azure DevOps, create a pipeline from this file, then add it as a build validation policy on main (Project settings > Repositories > dashboards > Policies > main). Azure Repos ignores the YAML pr: trigger, so the policy is what runs it on every pull request.

Or with the Azure CLI

Push azure-pipelines.yml to main first, then create the pipeline and the policy:

ORG=https://dev.azure.com/contoso
PROJECT=Monitoring

PIPELINE_ID=$(az pipelines create --org $ORG --project $PROJECT \
  --name dashboards-preview --repository dashboards --repository-type tfsgit \
  --branch main --yml-path azure-pipelines.yml --skip-first-run true \
  --query id -o tsv)

REPO_ID=$(az repos show --org $ORG --project $PROJECT --repository dashboards --query id -o tsv)

az repos policy build create --org $ORG --project $PROJECT \
  --repository-id $REPO_ID --branch main \
  --build-definition-id $PIPELINE_ID --display-name "Grafana dashboard previews" \
  --blocking true --enabled true \
  --manual-queue-only false --queue-on-source-update-only false --valid-duration 0
Enter fullscreen mode Exit fullscreen mode

--blocking true makes the run a required check, so a pull request with a broken dashboard can't complete. --valid-duration 0 keeps a successful run valid until the next push.


Step 3: Open a pull request

Change a dashboard in the UI or via code and push/save it to a branch.

Open a pull request into main. Watch the build validation run. After it's done, a comment will appear on the PR similar to this:

๐Ÿ“Š Grafana dashboard changes in this pull request

Dashboard Change Links
Service health
dashboards/platform/service-health.yaml
modified current ยท preview
Checkout funnel
dashboards/shop/checkout-funnel.yaml
added preview

Previews render <branch> without saving anything to Grafana. A new push can take a minute to reach the preview.

current opens the live dashboard. preview opens the dashboard from the pull request branch, with a button that leads back to the pull request:

Grafana preview of the Service health dashboard from the pull request branch. The new p95 latency panel shows under the existing Requests per second and Error rate panels, and a banner offers View saved version and View pull request in repository.

A dashboard that only exists on the branch gets a preview too:

Grafana preview of the new Checkout funnel dashboard, with Orders, Carts and Payments stats above a Conversion chart, and a banner saying the resource is loaded from the branch with a View pull request in repository button.

๐ŸŒฟ You can also run the pipeline on any branch. The task then lists every dashboard on that branch, with preview links, on the run's summary page.

Wrapping up

Azure DevOps may not be on Grafana's official list of supported providers, but with the azuredevops-proxy and git-sync-preview, it gets the Git Sync experience. Both projects are open source, so if you would like any feature added, issues and pull requests are your friends.

Bonus: HTTPS inside the cluster

If your cluster network does not come with encryption and you don't want to use allow_insecure in the Grafana setup, use an internal certificate in the cluster.

You'll need a self-signed issuer, a root certificate, a CA issuer and the proxy's certificate:

# internal-ca.yaml
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: selfsigned
spec:
  selfSigned: {}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: internal-root-ca
  namespace: cert-manager   # a CA ClusterIssuer reads its Secret from here
spec:
  isCA: true
  commonName: Internal Root CA
  secretName: internal-root-ca
  duration: 87600h   # 10 years
  privateKey:
    algorithm: ECDSA
    size: 256
  issuerRef:
    kind: ClusterIssuer
    name: selfsigned
---
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: internal-ca
spec:
  ca:
    secretName: internal-root-ca
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: git-proxy-internal-tls
  namespace: grafana
spec:
  secretName: git-proxy-internal-tls
  dnsNames:
    - git-proxy-git-v2-azuredevops-proxy.grafana.svc.cluster.local
  issuerRef:
    kind: ClusterIssuer
    name: internal-ca
Enter fullscreen mode Exit fullscreen mode
kubectl apply -f internal-ca.yaml
kubectl -n grafana wait certificate/git-proxy-internal-tls --for=condition=Ready
Enter fullscreen mode Exit fullscreen mode

The certificate creates a secret that holds tls.crt and tls.key for the proxy, and ca.crt, for Grafana to trust it. Add the Secret to git-proxy-helm-values.yaml. This will make the proxy change its service to its HTTPS port 8443:

tls:
  existingSecret: git-proxy-internal-tls
Enter fullscreen mode Exit fullscreen mode

In grafana-helm-values.yaml, turn allow_insecure off and give Grafana the ca.crt from that Secret:

grafana.ini:
  provisioning:
    allowed_git_urls: git-proxy-git-v2-azuredevops-proxy.grafana.svc.cluster.local
    allow_insecure: false

extraSecretMounts:
  - name: internal-ca
    secretName: git-proxy-internal-tls
    mountPath: /etc/grafana/internal-ca
    readOnly: true
    items:
      - key: ca.crt
        path: ca.crt

env:
  SSL_CERT_DIR: /etc/ssl/certs:/etc/grafana/internal-ca
Enter fullscreen mode Exit fullscreen mode
helm upgrade git-proxy oci://ghcr.io/dominik-esb/charts/git-v2-azuredevops-proxy \
  --version 2.2.0 -n grafana -f git-proxy-helm-values.yaml --wait
helm upgrade grafana grafana-community/grafana --version 14.5.0 -n grafana -f grafana-helm-values.yaml --wait
Enter fullscreen mode Exit fullscreen mode

Finally, point the repository at the HTTPS port. In Grafana, open the repository under Administration > Provisioning and change the URL to https://git-proxy-git-v2-azuredevops-proxy.grafana.svc.cluster.local:8443/dashboards.git. Grafana asks for the token again whenever the URL changes, so enter unused again.

As IaC

Change the URL and bump secureVersion in the same edit:

      git:
        url: https://git-proxy-git-v2-azuredevops-proxy.grafana.svc.cluster.local:8443/dashboards.git
  # ...
    secureVersion: 2
Enter fullscreen mode Exit fullscreen mode

Without bumping the secureVersion field, Crossplane reports a new token is required when changing the repository URL, and Grafana keeps the old URL.


Originally published at codejourney.io.

Top comments (0)