Skip to content
ImagineWorld

Automation with Infrastructure as Code

node_idnode-book_observability-with-grafana_chapter-10-automation-with-infrastructure-as-code
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleAutomation with Infrastructure as Code
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Automation with Infrastructure as Code

Section titled “Chapter 10 — Automation with Infrastructure as Code”

This chapter will explore how to use Infrastructure as Code (IaC) tools to automate the management of the various components of the Grafana observability platform. We will focus on Ansible, Terraform, and Helm, which allow teams to manage many aspects of their systems repeatably and automatically. This chapter divides the platform into the collection and processing layer, the storage layer, and the visualization layer and will outline how to automate each of these components. This chapter will provide the technical tools to create an easy-to-manage and very scalable observability platform, and combined with the information in Chapter 11, you will be well placed to lead your organization in easily leveraging the power of observability.

In this chapter, we’re going to cover the following main topics:

  • Benefits of automating Grafana
  • Introducing the components of observability systems
  • Automating collection infrastructure with Helm or Ansible
  • Getting to grips with the Grafana API
  • Managing dashboards and alerts with Terraform or Ansible

This chapter involves working with Ansible, Terraform, and Helm, and it is recommended that you install them before you start reading. The chapter will also discuss a couple of concepts that you should have at least a passing familiarity with:

  • Kubernetes objects
  • The Kubernetes operator pattern

Observability tooling combines the collection, storage, and visualization of telemetry from many applications, infrastructure services, and other components of systems. Automation offers us a way of providing a testable, repeatable way of delivering these needs. Using industry-standard tools such as Helm, Ansible, and Terraform helps us maintain these systems in the long term. There are a lot of benefits to using automation, including the following:

  • It reduces the risks associated with manual processes.
  • Domain experts can provide automation for systems that developers interact with. This gives development teams confidence that they are using unfamiliar systems correctly. This knowledge comes in the following forms:
    • Data architecture for telemetry
      • Repeatable system architecture
      • Best practices for managing data visualizations
  • By providing automation, domain experts are able to focus on higher-value work by letting teams self-serve using more straightforward and user-friendly systems.
  • It provides a golden path so development teams can adopt observability easily and quickly and spend more time focusing on value-adding activities.
  • It allows for easy scaling of best practices and operational processes. This is especially important for organizations that are growing, where a process that may work with a handful of teams does not scale to dozens of teams.
  • It ensures that cost information is always attributable.

Now that we’ve introduced why you would want to use automation, let’s have a look at the components that make up an observability platform so we can easily automate the different aspects of the system.

Introducing the components of observability systems

Section titled “Introducing the components of observability systems”

Observability systems consist of many components involved in producing, consuming, transforming, storing, and using data. Over the course of this chapter, we will split these components into four distinct systems to be clear about which aspect of observability platforms we are discussing. The different aspects of automation will be of interest to different audiences. The systems we will discuss are as follows:

  1. Data production systems: These are the systems that generate data. The applications, infrastructure, and even components of the data collection system will produce data. Let’s look at the key features:
    • These systems are managed by developers such as Diego, or by operations experts such as Ophelia (refer to Chapter 1 for details on these personas).
      • These systems are tested as part of the application- or component-testing process. If a data schema is in use, this can be validated using a tool such as JSON Schema.
  2. Data collection systems: These systems collect the logs, metrics, and traces generated by data-producing systems. They typically offer tools for transforming data. Their key features are the following:
    • These systems are often run by specialist operations teams, observability engineers, site reliability engineers, or platform engineers
      • These systems are provisioned infrastructure
      • Automation involves the use of IaC tools and static analysis tools (where available) to validate the infrastructure
  3. Data storage systems: These are the systems that store data and make it searchable. If your observability platform leverages SaaS tools, these systems will be provided by your vendor. Loki, Prometheus, Mimir, and Tempo are all examples of storage systems. Some of the important features of these systems include the following:
    • These systems are often managed by dedicated third parties, but when they are managed within an organization, they will typically be managed by the same team as the data collection system
      • These systems are provisioned infrastructure
      • Automation involves the use of IaC to provision on-prem resources, or leverages SaaS tooling such as Grafana Labs with IaC configuration
  4. Data visualization systems: These are the systems that allow users to search the data stored in the storage systems and produce visualizations, alerts, and other methods of understanding the data. Grafana is an example of a visualization system. The following are some important features of such systems:
    • The management of this layer is typically a shared responsibility. The developers and operators who manage a particular system should be empowered to take ownership of their dashboards. The team managing the collection and storage layers will typically be the team empowering the rest of the organization.
      • These systems are provisioned infrastructure.
      • Automation involves the use of IaC to provision on-prem resources, or leveraging SaaS tooling such as Grafana Labs, with IaC configuration.

In this chapter, we will discuss systems 2, 3, and 4 in the preceding list. System 1, while important, is a very broad area and the automation strategies differ for different types of data producers. However, in most cases, teams can rely on the testing done by the libraries they consume, or the third-party systems they run.

Let’s start by looking at how we can use Terraform or Ansible to deploy data collection systems.

Automating collection infrastructure with Helm or Ansible

Section titled “Automating collection infrastructure with Helm or Ansible”

Automating the installation of the infrastructure used to collect telemetry is a critical piece of building a great observability platform. The tools to support this depend on the infrastructure you are deploying to. In this section, we will examine the installation of the OpenTelemetry Collector and Grafana Agent using the following tools:

  • Helm is a tool for packaging and managing Kubernetes applications. A Helm chart contains all the configuration files for the various Kubernetes components needed for an application, and typically handles setting the variables for the application. We will be using Helm in a Kubernetes environment.
  • Ansible is a tool for standardizing operations into repeatable playbooks. It uses simple YAML configuration files to define the actions to be taken and leverages OpenSSH to connect to the target servers on which the actions are to be taken. We’ll be using Ansible in a virtual or bare-metal environment, but it can be used to manage Kubernetes environments as well.

Important note

OpenTelemetry and Grafana both offer a Kubernetes operator, which can be installed using Helm. We will provide an overview of these tools as well.

Now let’s look at how we can use Helm and Ansible to automate the installation of the OpenTelemetry Collector and Grafana Agent.

Automating the installation of the OpenTelemetry Collector

Section titled “Automating the installation of the OpenTelemetry Collector”

In this book, we have been using the OpenTelemetry Collector to collect data from the OpenTelemetry demo application and send it into our Grafana instance. First, we’ll use the configuration we have already deployed to explore using the Helm chart made by OpenTelemetry to deploy the collector into a Kubernetes cluster.

We first installed the OpenTelemetry Helm chart in Chapter 3, and then updated the configuration in Chapters 4, 5, and 6. OpenTelemetry provides detailed information about the configuration options that are available in its Git repository at https://github.com/open-telemetry/opentelemetry-helm-charts/tree/main/charts/opentelemetry-collector.

Let’s look at the final configuration that we applied in Chapter 6 and see how we configure the OTEL Helm chart. You can find this file in the Git repository at /chapter6/OTEL-Collector.yaml.

The first configuration block we’ll look at is mode, which describes how the collector is going to be deployed in Kubernetes. The options available are deployment, daemonset, and statefulset. Here, we use the deployment option:

mode: deployment

Let’s explore the available options in some detail:

  • A deployment is deployed with a fixed number of Pods, which is the replicaCount in Kubernetes terms. For our reference system, we used this mode as we know the system will be deployed to a single-node Kubernetes cluster, and it allows us to combine presets that would usually be used independently in a multi-node cluster.
  • A daemonset is deployed with a collector to every node in a cluster.
  • A statefulset is deployed with unique network interfaces and consistent deployments.

We discuss selecting the appropriate mode in Chapter 11 when we discuss architecture. These deployment modes can also be combined to provide specific functionality in a Kubernetes cluster.

The next configuration block we’ll look at is presets:

presets:
logsCollection:
enabled: true
includeCollectorLogs: false
kubernetesAttributes:
enabled: true
kubernetesEvents:
enabled: true
clusterMetrics:
enabled: true
kubeletMetrics:
enabled: true
hostMetrics:
enabled: true

As you can see, this configuration involves simply enabling or disabling different functions. Let’s look at the parameters in detail:

  • The logsCollection parameter tells the collector to collect logs from the standard output of Kubernetes containers. We are not including the collector logs as this can cause a logging cascade, where the collector reads its own log output and writes the collected logs to that output, which are then read again. In real-life setups, it is recommended to only use the logsCollection parameter in daemonset mode.
  • The kubernetesAttributes parameter collects Kubernetes metadata as the collector receives logs, metrics, and traces. This includes information such as k8s.pod.name, k8s.namespace.name, and k8s.node.name. The attribute collector is safe to use in all modes.
  • The kubernetesEvents parameter collects the events that occur in the cluster and publishes them in the log pipeline. Effectively, every event that occurs in the cluster receives a log entry in Loki with this configuration. Cluster events include things such as Pod creations and deletions, among others. It’s best practice to use kubernetesEvents in the deployment or statefulset modes to prevent the duplication of events.
  • The three metrics options collect metrics about the system:
    • clusterMetrics looks at the full cluster. This should be used in deployment or statefulset modes.
      • kubeletMetrics collects metrics from the kubelet about the node, Pods, and containers it is managing. This should be used in daemonset mode.
      • hostMetrics collects data directly from the host, such as CPU, memory, and disk usage. This should be used in daemonset mode.

We’ll skip over a few blocks that are standard Kubernetes configurations and consider the config block next. The config block has a few subblocks:

  • The telemetry pipeline includes the following:
    • receivers: Receivers are at the start of a pipeline. They receive data and translate it to add it to the pipeline for other components to use.
      • processors: Processors are used in a pipeline to carry out various functions. There are supported processors and contributed processors available.
      • exporters: Exporters come at the end of a pipeline. They receive data in the internal pipeline format and translate it to send the data onwards.
      • connectors: These combine receivers and exporters to link pipelines together. connectors act as exporters to send the data from one pipeline onwards, and as receivers to take that data and add it to another pipeline.
  • Separate to the pipeline are extensions, which add additional functionality to the collector, but do not need access to the telemetry data in the pipelines.
  • Finally, there is a service block, which is used to define the pipelines and extensions in use.

The only extension we are using in our config block is the health_check extension:

config:
extensions:
health_check:
check_collector_pipeline:
enabled: false

This enables an endpoint that can be used for a liveness and/or readiness probe in the Kubernetes cluster. This is helpful for you to be able to see easily whether the collector is working as expected.

In our receivers block we have configured two receivers, otlp and prometheus:

config:
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:4318
cors:
allowed_origins:
- "http://*"
- "https://*"
prometheus:
config:
scrape_configs:
- job_name: 'opentelemetry-collector'
tls_config:
insecure_skip_verify: true
scrape_interval: 10s
scrape_timeout: 2s
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: "true"
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
target_label: __address__
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $$1:$$2

Let’s look at these receivers more closely:

  • The OTLP receiver configures our collector instance to expose port 4318 on 127.0.0.1 on the Kubernetes node, which allows the demo applications to submit telemetry easily.
  • The Prometheus receiver is used to collect metrics from the collector itself. This receiver config shows an example of relabeling, where we take meta_kuberentes_pod_annotation_prometheus_io_port and rename it with __address__, which is the standard used in OTLP.

In our configuration, we have set up the k8sattributes, resource, and attributes processors. The k8sattributes processor extracts attributes from the kubelet and adds them to the telemetry in the pipelines. The resource and attributes processors will insert or modify the resource or attributes respectively. We’ll not discuss these concepts in detail, but resources are used to identify the source that is producing telemetry.

In our configuration, we are using both the spanmetrics and servicegraph connectors:

config:
connectors:
spanmetrics:
dimensions:
- name: http.method
default: GET
- name: http.status_code
namespace: traces.spanmetrics
servicegraph:
latency_histogram_buckets: [1,2,3,4,5]

Both connectors are used to export the data from the traces pipeline and receive it in the metrics pipeline. spanmetrics collects the request, error, and duration (RED) metrics from the span data (we introduced RED in Chapter 9). servicegraph generates metrics that describe the relationship between services, these metrics allow the service graphs to be shown in Tempo.

The final subblock in our config block is services. This subblock defines the extensions to be loaded and the configuration of the pipelines. Each pipeline (logs, metrics, and traces) defines the receivers, processors, and exporters used. Let’s look at the metrics pipeline as it is the most complex:

metrics:
receivers:
- otlp
- spanmetrics
- servicegraph
processors:
- memory_limiter
- filter/ottl
- transform
- batch
exporters:
- prometheusremotewrite
- logging

The receivers are OTLP, spanmetrics, and servicegraph as discussed previously. We then instruct the pipeline to use the memory_limiter, filter, transform, and batch processors, in the order listed. You may notice that our filter is named ottl using the syntax of processor/name, which is useful when you need to use the same processor with different configurations. Finally, the pipeline uses the prometheusremotewrite exporters and logging to output data.

You may have noticed that the exporters are not defined in the /chapter6/OTEL-Collector.yaml file – this is because they are defined in /OTEL-Creds.yaml, and this highlights a very useful feature of Helm, which is the ability to separate out configuration files based on their function. When we install the Helm chart, we use a command such as the following:

helm install owg open-telemetry/opentelemetry-collector --values chapter3/OTEL-Collector.yaml --values OTEL-Creds.yaml

The -f or --values option can be used multiple times for multiple YAML files – if there are conflicts, then precedence is always given to the last file used. By structuring the YAML files in such a way, we can split the full configuration in ways that allow us to protect secret information, such as API keys, while still making our main configuration easily available. We can also use this feature for other purposes such as overriding a default configuration in a test environment. It’s important to be careful with precedence here as duplicate arrays will not be merged. Deploying the collector in this way is fantastic in a lot of situations. However, it has a limitation – any time there is a change to the configuration, or a new version of the collector is to be installed, a Helm install or upgrade operation needs to be carried out. This introduces the need for a system that has knowledge of and access to each cluster in which the collector will be deployed, which can introduce bottlenecks and security risks. Let’s look at the OpenTelemetry Operator, which offers solutions to these problems.

OpenTelemetry also offers a Kubernetes operator to manage both the OpenTelemetry Collector and allow for auto-instrumentation of workloads. This operator is still in active development and the feature set is expected to increase.

Kubernetes operators use Custom Resource Definitions (CRDs) to provide extensions to the Kubernetes API, which are used by the operators to manage the system. The advantages of using an operator include the following:

  • The complex logic involved in managing the OpenTelemetry Operator or the auto-instrumentation system can be designed by the experts working on the OpenTelemetry projects. For the person responsible for managing an OpenTelemetry installation, the operator offers a defined CRD specification against which to validate the proposed configuration in a CI/CD pipeline.
  • The OpenTelemetry operator also allows for limited automated upgrades. Minor and major version updates still need to be applied via a Helm upgrade due to the possibility of breaking changes.
  • It can be combined with GitOps tooling to move from a solution where a central system must know each cluster and have the necessary credentials to deploy to them, to a solution where each cluster reads the desired configuration from a central version-controlled repository.
  • The operator really excels when it comes to making the OpenTelemetry auto-instrumentation easily accessible to applications by adding annotations. For the majority of use cases, auto-instrumentation will provide ample metric and trace telemetry to understand an application.

The OpenTelemetry Collector can also be installed on virtual or bare-metal servers, this process can be automated with tools such as Ansible. Let’s see how you might approach this.

OpenTelemetry does not provide an official collection for Ansible. It provides packaged versions of the collector for Alpine-, Debian-, and Red Hat-based systems as .apk, .deb, and .rpm files respectively. Using community.general.apk, ansible.builtin.apt, or ansible.builtin.yum, the package can be installed with a configuration similar to the following:

- name: Install OpenTelemetry Collector
ansible.builtin.apt:
deb: https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.85.0/otelcol_0.85.0_linux_amd64.deb

With the package installed, the only other thing to do to configure the collector is to apply a configuration file. The default configuration file is located at /etc/otelcol/config.yaml and is used when systemd starts the collector. Ansible can overwrite this file or modify it in place. This could be done with the following configuration:

- name: Copy OpenTelemetry Collector Configuration
ansible.builtin.copy:
src: /srv/myfiles/OTEL-Collector.yaml
dest: /etc/otelcol/config.yaml
owner: root
group: root
mode: '0644'

We have looked at the OpenTelemetry agent a lot during this book. One major reason for this is that OpenTelemetry also offers the Demo application we have used to produce realistic sample data. Next, let’s take a look at Grafana Agent.

Automating the installation of Grafana Agent

Section titled “Automating the installation of Grafana Agent”

Grafana produces its own agent, which is recommended by Grafana for use with its cloud platform. Grafana Agent also provides automation options, which we will introduce in this section.

Grafana offers two Helm charts, the grafana-agent chart and the agent-operator chart. Similar to the OpenTelemetry charts, the Agent chart allows for a direct installation of the Grafana Agent on a Kubernetes cluster. The Operator chart deploys CRDs into the cluster and then manages the state of the Agent based on these definitions. At the time of writing, the Grafana Agent Operator offers CRDs for metrics and log collection. For full details of the grafana-agent chart and the configuration options, please check out the Helm chart documentation at https://github.com/grafana/agent/tree/main/operations/helm/charts/grafana-agent. Similarly, the documentation for the agent-operator chart can be found at https://github.com/grafana/helm-charts/tree/main/charts/agent-operator#upgrading-an-existing-release-to-a-new-major-version. Details of the available CRDs are documented in the Operator architecture documentation at https://github.com/grafana/agent/blob/v0.36.2/docs/sources/operator/architecture.md.

Unlike OpenTelemetry, Grafana maintains an Ansible collection (https://docs.ansible.com/ansible/latest/collections/grafana/grafana) that includes tools to manage collection, storage, and visualization systems, and we will revisit it in later sections.

The included grafana_agent role is used to manage data collection and will install the agent on Red Hat, Ubuntu, Debian, CentOS, and Fedora distributions. This role can be used as follows:

- name: Install Grafana Agent
ansible.builtin.include_role:
name: grafana_agent
vars:
grafana_agent_logs_config:
<CONFIG>
grafana_agent_metrics_config:
<CONFIG>
grafana_agent_traces_config:
<CONFIG>

The configuration for logs, metrics, and traces is specific to that telemetry type and the documentation available from Grafana covers using that configuration to manage the Agent.

Grafana offers a full-featured API for both Grafana Cloud and Grafana itself. This API is the same API used by the frontend, which means that we can also drive the functions of Grafana using either direct API calls in a script, or an IaC tool such as Terraform. We’ll start by having a high-level look at the APIs available in Grafana Cloud and Grafana, then we’ll look at the Grafana Terraform module and the Ansible collection, and see how to use them to manage a Grafana Cloud instance.

The Grafana Cloud API is used to manage all aspects of a Grafana Cloud SaaS installation. Let’s have a high-level look at the functions provided by the Grafana Cloud API:

  • Access policies and tokens: These API endpoints manage authentication and authorization resources. Here are their major functions:
    • Create, read, update, and delete functions for access policies
      • Create, read, update, and delete functions for tokens Tokens must be associated with an accessPolicyId, which is the unique ID for an access policy object.
  • Stacks: These endpoints manage Grafana Cloud stacks. The following are their key functions:
    • Create, read, update, and delete functions for stacks
      • Restart Grafana on a specific stack
      • List data sources on a specific stack
  • Grafana plugins: These endpoints manage plugins installed on Grafana instances related to a stack. Their functions include creating, reading, updating, and deleting functions for Grafana plugins installed on a specific stack.
  • Regions: These API endpoints list the Grafana Cloud regions available. They are used to read functions for the available Grafana Cloud regions that can be used to host a stack.
  • API keys: These endpoints were for managing Cloud API keys and their major functions are the create, read, and delete functions for API keys. These endpoints are now deprecated as Grafana has moved to authentication techniques using access policies and tokens. API key endpoints will be removed in a future update.

We will discuss access policies and tokens in more detail in Chapter 11 where we discuss access levels as part of architecting a great observability platform. All the Grafana Cloud endpoints have an associated access policy, and the token used must be authorized with that policy for a successful response.

More detailed information is available in Grafana’s documentation at https://grafana.com/docs/grafana-cloud/developer-resources/api-reference/cloud-api/, including information on the parameters and details needed in a request as well as example requests and responses.

We’ve now reviewed the API endpoints. Next, we’ll discuss Grafana’s offerings of both a Terraform provider and the Ansible collection, which can be used to interact with the aforementioned APIs using IaC automation.

Using Terraform and Ansible for Grafana Cloud

Section titled “Using Terraform and Ansible for Grafana Cloud”

Grafana provides both a Terraform provider and an Ansible collection for use in managing organizations’ Cloud instances. Let’s explore how we can use these tools with the Grafana Cloud API to manage a Grafana Cloud instance.

The Grafana Terraform provider has resources that match the Cloud API endpoints we have discussed. The provider also offers resources for other Grafana API endpoints, which we will cover when we discuss managing dashboards and alerts later in this chapter. The official documentation for the provider can be found on the Terraform Registry at https://registry.terraform.io/providers/grafana/grafana/latest/docs.

Important note

This chapter was written with version 2.6.1 of the Grafana Terraform provider.

Here are some of the commonly used Terraform resources with examples of their use:

  • First, let’s have a look at using the provider. The grafana_cloud_stack data provider is used to find a stack called acme-preprod, which we will use later to specify where our access policy is to
    data "grafana_cloud_stack" "preprod" {
    slug = "acme-preprod"
    }
  • The grafana_cloud_access_policy resource allows us to create an access policy. Here, we set our region value to us, along with a name and a display name. Finally, we specify the scope of the policy – in this case, we want to be able to write logs, metrics, and traces. The stack ID we found earlier is then used to specify where to create this access policy:
    resource "grafana_cloud_access_policy" "collector-write" {
    region = "us"
    name = "collector-write"
    display_name = "Collector write policy"
    scopes = ["logs:write", "metrics:write", "traces:write"]
    realm {
    type = "stack"
    identifier = data.grafana_cloud_stack.preprod.id
    }
    }
  • Finally, the grafana_cloud_access_policy_token resource can be used to create a new token. We specify a region, the access policy to use, and a name. The token will then be able to be read grafana_cloud_access_policy_token.collector-token.token
    resource "grafana_cloud_access_policy_token" "collector-token" {
    region = "us"
    access_policy_id = grafana_cloud_access_policy.collector-write.policy_id
    name = "preprod-collector-write"
    display_name = "Preprod Collector Token"
    expires_at = "2023-01-01T00:00:00Z"
    }

This isn’t the only thing we can do with the Grafana Terraform provider: we’ll consider another example later in this chapter when we examine managing dashboards and alerts. Typically, this would be combined with another provider to record this newly created token in a secrets management tool, such as AWS Secrets Manager or HashiCorp Vault, where it can be accessed whenever a collector is deployed.

Let’s look managing a Grafana Cloud system with another IaC tool provided by Grafana, the Grafana Ansible collection.

The Grafana Ansible collection is not as feature rich as the Terraform provider for managing cloud instances. However, a lot of the functionality from the Grafana Cloud API can be accessed using the Ansible URI module. The official collection documentation is available on the Ansible site at https://docs.ansible.com/ansible/latest/collections/grafana/grafana/. A community-provided collection is also available, but will not be discussed here. The relevant documentation is available at https://docs.ansible.com/ansible/latest/collections/community/grafana/index.html.

Important note

This chapter was written with version 2.2.3 of the Grafana Ansible collection.

We’ll look at managing a Grafana Cloud stack using Ansible. The name and stack_slug (this is the stack we are interacting with) values are set to the same string by convention. We then need to set the region value for the stack, along with the organization the stack will belong to using org_slug:

- name: Create preprod stack
grafana.grafana.cloud_stack:
name: acme-preprod
stack_slug: acme-preprod
cloud_api_key: "{{ grafana_cloud_api_key }}"
region: us
org_slug: acme
state: present

We’ve so far looked at the API for Grafana Cloud. This API is great for managing an observability platform in Grafana Cloud, but a lot of teams will be more interested in managing dashboards, alerts, and other items in the Grafana UI. Grafana provides another API to manage objects in the Grafana UI – let’s look at it now.

While the Grafana Cloud API is only used to manage Grafana Cloud SaaS instances, the Grafana API is very far reaching as Grafana has a lot of functionality. These APIs can be used on both Grafana Cloud and locally installed Grafana instances.

Similar to the Grafana Cloud API, all endpoints use role-based access control. However, the Grafana API offers an additional authentication option: service accounts. Service accounts should be used for any application that needs to interact with Grafana.

As most teams will use a small subset of APIs frequently, we will only discuss a few APIs here. However, there are a lot of other APIs that can be used to automate the management of a Grafana instance. Let’s take a closer look at some commonly used APIs:

  • Dashboard and Folder: These endpoints manage dashboards and folders in Grafana. Their functions include the following:
    • Create, read, update, and delete functions for dashboards or folders
      • Create, read, update, and delete the tags on a dashboard Dashboards and folders have both an ID and a UID. The ID is only unique to a specific Grafana installation, while the UID is unique across installations.
  • Dashboard Permissions and Folder Permissions: These APIs handle the access controls for dashboards and folders. They can be used to update permissions for a dashboard or folder. These endpoints use a UID, although there is a deprecated endpoint to update permissions for dashboards by ID. Permissions are set numerically: 1 = View, 2 = Edit, 4 = Admin. Permissions can be set for user roles or teamId values.
  • Folder/Dashboard Search: This API allows users to search for dashboards and folders. This endpoint allows for complex searches using query parameters. The response is a list of matching objects including the UID of an object.
  • Teams: These endpoints manage Teams in Grafana. They can be used to do the following:
    • Create, read, update, and delete teams
      • Get, add, and remove team members
      • Get and update team preferences
  • Alerting: These complex APIs manage all of the aspects of alerts. This API manages everything to do with Grafana Alertmanager. It can be used to create, read, update, and delete alerts, alert rules, alert groups, silences, receivers, templates, and many more alerting objects.

These API endpoints are fantastic for managing Grafana. Grafana provides a detailed API reference at https://grafana.com/docs/grafana/latest/developers/http\_api/.

Let’s now look at how these API endpoints allow us to use the IaC tools of Terraform and Ansible to manage dashboards and alerts.

Managing dashboards and alerts with Terraform or Ansible

Section titled “Managing dashboards and alerts with Terraform or Ansible”

As dashboards are typically managed by the teams responsible for a service or application, it is best practice to separate the tooling to deploy dashboards from the tooling to manage observability infrastructure. We will discuss the practicalities of this in Chapter 14.

For managing dashboards, both Terraform and Ansible leverage the fact that Grafana dashboards are JSON objects, providing a mechanism to upload a JSON file with the dashboard configuration to the Grafana instance. Let’s look at how this works.

The Terraform code looks like this:

resource "grafana_dashboard" "top_level " {
config_json = file("top-level.json")
overwrite = true
}

A collection of dashboard JSON files can be iterated over using the Terraform fileset function with a for_each command. This makes it very easy for a team to manage all its dashboards in an automated manner by saving the correct dashboard to the relevant folder.

The Ansible collection works in a very similar fashion:

- name: Create Top Level Dashboard
grafana.grafana.dashboard:
dashboard: "{{ lookup('ansible.builtin.file', ' top-level.json') }}"
grafana_url: "{{ grafana_url }}"
grafana_api_key: "{{ grafana_api_key }}"
state: present

Like the Terraform code, this could be iterated using the built-in with_fileglob function, allowing teams to manage all their dashboards in an automated fashion.

Unfortunately, with the latest changes to alerting in Grafana, the Ansible collection has not been updated to allow for alert management. With Terraform, you can manage Grafana Alerts in a very similar way to dashboards. Consider the following example code block:

resource "grafana_rule_group" "ateam_alert_rule" {
name = "A Team Alert Rules"
folder_uid = grafana_folder.rule_folder.uid
interval_seconds = 240
org_id = 1
rule {
name = "Alert Rule 1"
}
rule {
name = "Alert Rule 2"
}

We’ve not included the full details of the two rules shown here as the required configuration block is too large. The Terraform documentation has a very clear example of a full alert at https://registry.terraform.io/providers/grafana/grafana/latest/docs/resources/rule\_group.

Similar to the grafana_dashboard resource, grafana_rule_group can be iterated over by using a dynamic block to populate each rule from another source, such as a JSON file, for example. This makes the management of these rules significantly more user-friendly.

In this chapter, you were introduced to the benefits of automating the management of your observability platform, and saw how investing in good automation can allow subject-matter experts to shift repetitive and low-value work to others in the organization. We discussed the different aspects of observability platforms, being data production, collection, storage, and visualization. You also learned who is typically responsible for each aspect of the platform.

With the theory largely covered, we then went on to discuss how to manage the data collection layer, presenting an in-depth analysis of the OpenTelemetry Collector Helm configuration that has been used to collect data throughout this book. We contrasted the way Helm works with Ansible to deploy to a virtual or physical setup, and you gained valuable skills in understanding the structure of the management files used by each tool. We rounded out the automation of data collection systems by introducing the Helm chart and the Ansible collection for Grafana Agent. While we did not go into this in the same depth as the OpenTelemtry configuration, the skills required for managing the Grafana Agent are identical.

Our next topic was the Grafana API, where you learned that there are two APIs, one to manage the SaaS Grafana Cloud solution, and one to manage Grafana instances (both cloud and local). You were then introduced to the Terraform provider for Grafana and learned through specific examples how to manage both their cloud stacks and their Grafana instances. We then also looked at the Grafana Ansible collection and saw how it can be used to manage cloud stacks and Grafana instances as well as the data collection layer.

In the next chapter of this book, we will discuss how to architect a full observability platform that scales to the needs of your organization.