Skip to content
ImagineWorld

Interrogating Infrastructure with Kubernetes, AWS, GCP, and Azure

node_idnode-book_observability-with-grafana_chapter-07-interrogating-infrastructure-with-kubernetes-aws-gcp-and-azu
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleInterrogating Infrastructure with Kubernetes, AWS, GCP, and Azure
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Interrogating Infrastructure with Kubernetes, AWS, GCP, and Azure

Section titled “Chapter 7 — Interrogating Infrastructure with Kubernetes, AWS, GCP, and Azure”

This chapter will introduce the setup and configuration required to capture telemetry from various common cloud infrastructure providers. You will learn about the different options available for Kubernetes. Additionally, you will investigate the main plugins that allow Grafana to query data from cloud vendors such as Amazon Web Services (AWS), Google Cloud Platform (GCP), and Azure. You will look at solutions for handling large volumes of telemetry where direct connections are not scalable. The chapter will also cover options for filtering and selecting telemetry data before it gets to Grafana for security and cost optimization.

We will cover the following main topics in this chapter:

  • Monitoring Kubernetes using Grafana
  • Visualizing AWS telemetry with Grafana Cloud
  • Monitoring GCP using Grafana
  • Monitoring Azure using Grafana
  • Best practices and approaches

In this chapter, you will work with multiple cloud providers using a Grafana Cloud instance. You will need the following:

  • A Grafana Cloud instance (set up in Chapter 3)
  • Kubernetes and Helm (set up in Chapter 3)
  • Accounts with the AWS, GCP, and Azure cloud providers with admin-level permissions

Kubernetes has been designed to be monitored, and as such, it presents multiple options for anyone wanting to monitor it or the workloads running on it using Grafana. In this section, we will focus on monitoring Kubernetes, as we have already worked with Kubernetes workloads in previous chapters using the OpenTelemetry Demo application.

The OpenTelemetry Collector introduced in Chapter 3 provides receivers, processors, and exporters to implement Kubernetes monitoring with data collection and enrichment. The following table identifies those components with a brief explanation for each of them:

OpenTelemetry ComponentDescription
Kubernetes Attributes ProcessorThe Kubernetes Attributes Processor appends Kubernetes metadata to telemetry, providing the necessary context for correlation.
Kubeletstats ReceiverThe Kubeletstats Receiver obtains Pod metrics via a pull mechanism from the kubelet API. It collects node and workload metrics from each node it is installed on.
Filelog ReceiverThe Filelog Receiver collects Kubernetes and workload logs that are written to stdout and stderr.
Kubernetes Cluster ReceiverThe Kubernetes Cluster Receiver collects cluster-level metrics and entity events using the Kubernetes API.
Kubernetes Object ReceiverThe Kubernetes Object Receiver collects objects for example events from the Kubernetes API.
Prometheus ReceiverThe Prometheus Receiver scrapes metrics using Prometheus scrape_config settings.
Host Metrics ReceiverThe Host Metrics Receiver scrapes metrics from Kubernetes nodes.

Table 7.1 – Kubernetes receivers

Let’s now explore each component and how to implement them.

The OpenTelemetry Kubernetes Attributes Processor can automatically discover Pods, extract metadata from them, and add the extracted metadata to spans, metrics, and logs as additional resource attributes. It provides necessary context to your telemetry, enabling the correlation of your application’s metrics, events, logs, traces, and signals with your Kubernetes telemetry, such as Pod metrics and traces.

Data passing through the processor is by default associated to a Pod via the incoming request’s IP address, but different rules can be configured.

The OpenTelemetry Collector Helm chart comes with several presets. For instance, the kubernetesAttributes preset, when enabled, will add the necessary RBAC roles to a ClusterRole and will add a k8sattributesprocessor to each enabled pipeline:

presets:
kubernetesAttributes:
enabled: true

Kubernetes comes with its own metadata to document its components. When using the kubernetesAttributes preset, the following attributes are added by default:

  • k8s.namespace.name: The namespace the Pod is deployed to.
  • k8s.pod.name: The name of the Pod.
  • k8s.pod.uid: The unique ID for the Pod.
  • k8s.pod.start_time: The timestamp for Pod creation, useful when understanding Pod restarts.
  • k8s.deployment.name: The Kubernetes deployment name for the application.
  • k8s.node.name: The name of the node the Pod is running on. As Kubernetes distributes the Pods over all of its nodes, it is important to understand whether any are having specific problems.

Additionally, the Kubernetes Attributes Processor creates custom resource attributes for your telemetry using Pod and namespace labels and annotations.

There are two methods applied to obtain and associate your data, that is, extract and pod_association. You can enable them in your Helm chart as detailed in the following code:

k8sattributes:
auth_type: 'serviceAccount'
extract:
pod_association:

Let’s look at these methods in greater detail:

  • extract: This method provides the ability to use metadata, annotations, and labels as resource attributes for your telemetry. It has the
    • metadata: Used to extract values from the Pod and namespace, such as k8s.namespace.name and k8s.pod.name
      • annotations: Used to extract the value of a Pod or namespace annotation with a key and insert it as a
      - tag_name: attribute-name
      key: annotation-name
      from: pod
      • labels: Used to extract the value of a Pod or namespace label with a key and insert it as a
      - tag_name: attribute-name
      key: label-name
      from: pod
    Both annotations and labels can also be used with regex to extract part of the value for the new resource attribute.
  • pod_association: This method associates data with the relevant Pod. You can configure multiple sources and the agent will try them in order, stopping when it finds a match. pod_association has the sources option, which is used to identify the resource attribute to use for the association, or it uses the IP attribute from the
    pod_association:
    - sources:
    - from: resource_attribute
    name: k8s.pod.ip
    - sources:
    - from: resource_attribute
    name: k8s.pod.uid
    - sources:
    - from: connection

Permissions

If you are not using the kubernetesAttributes preset, you will have to provide the necessary permissions to allow access to the Kubernetes API. Usually, being able to access Pod, namespace, and ReplicaSet resources is adequate, but this will depend upon your cluster configuration.

The Kubeletstats Receiver connects to the kubelet API to collect metrics about the node and the workloads running on the node, which is why the preferred deployment mode is DaemonSet. Metrics are collected for Pods and nodes by default but can additionally be configured to collect metrics from containers and volumes.

The following code shows the configuration of the Kubeletstats Receiver:

receivers:
kubeletstats:
collection_interval: 60s
auth_type: 'serviceAccount'
endpoint: '${env:K8S_NODE_NAME}:10250'
insecure_skip_verify: true
metric_groups:
- node
- pod
- container

Although not a Kubernetes-specific receiver, the Filelog Receiver is the most popular log collection mechanism for Kubernetes. It tails and parses logs from files using operators chained together to process log data.

The OpenTelemetry Collector Helm chart has the logsCollection preset to add the necessary RBAC roles to the ClusterRole, and it will add a filelogreceiver instance to each enabled pipeline (we will explain includeCollectorLogs in Chapter 10):

presets:
logsCollection:
enabled: true
includeCollectorLogs: false

If configuring this yourself, you will have to add the roles and filelogreceiver into your pipelines manually. A basic Filelog Receiver shows what to include and exclude, along with additional processing options:

filelog:
include:
- /var/log/pods/*/*/*.log
exclude:
- /var/log/pods/*/otel-collector/*.log
start_at: beginning
include_file_path: true
include_file_name: false

Additionally, operators can be applied for log processing, filtering, and parsing.

The following is a list of Filelog Receiver parsers:

  • json_parser: To parse JSON
  • regex_parser: To perform regular expression parsing
  • csv_parser: To parse comma-separated values
  • key_value_parser: To process structured key-value pairs
  • uri_parser: To process structured web paths
  • syslog_parser: To process the standard syslog log format

The Kubernetes Cluster Receiver, as its name suggests, collects metrics and events from the cluster using the Kubernetes API server. This receiver is used to obtain information regarding Pod phases, node conditions, and other cluster-level operations. The receiver must be deployed as a single instance; otherwise, the data would be duplicated.

An example cluster receiver configuration follows:

k8s_cluster:
auth_type: serviceAccount
node_conditions_to_report:
- Ready
- MemoryPressure
allocatable_types_to_report:
- cpu
- memory
metrics:
k8s.container.cpu_limit:
enabled: false
resource_attributes:
container.id:
enabled: false

The Kubernetes Objects Receiver can be used to collect any type of object from the Kubernetes API server. As with the Kubernetes Cluster Receiver, this must be deployed as a single instance to prevent duplicate data.

The receiver can be implemented to pull or watch objects by using pull or watch:

  • When pull is implemented, the receiver periodically polls the Kubernetes API and lists all the objects in the cluster. Each object will be converted to its own log.
  • When watch is configured, the receiver creates a stream with the Kubernetes API to receive updates as and when objects change; this is the most common use case.

Let’s look at an example of Kubernetes Object Receiver configuration:

k8sobjects:
auth_type: serviceAccount
objects:
- name: pods
mode: pull
label_selector: environment in (prod)
field_selector: status.phase=Running
interval: 15m
- name: events
mode: watch
group: events.k8s.io
namespaces: [default]

The Prometheus Receiver can be used to collect (scrape) metrics from Kubernetes and its workloads. The full range of Prometheus scrape_config options are supported by the receiver. An example of this implementation and scrape_configs can be seen in the Chapter 5 demo project code. Here is an example Prometheus Receiver configuration:

prometheus:
config:
scrape_configs:
- job_name: 'opentelemetry-collector'
tls_config:
insecure_skip_verify: true
scrape_interval: 60s
scrape_timeout: 5s
kubernetes_sd_configs:
- role: pod

The Prometheus Receiver is stateful, so the following points need to be taken into consideration when using it:

  • The receiver cannot auto-scale the scraping process with multiple replicas
  • Running multiple replicas with the same config will scrape targets multiple times
  • To manually scale the scraping process, each replica will need to be configured with a different scraping configuration

The Host Metrics Receiver collects metrics from a host using a variety of scrapers; the receiver will need access to the host filesystem volume to work correctly.

Table 7.2 shows the metrics available to scrape. The OpenTelemetry Collector Helm chart has the hostMetrics preset to add the necessary configurations:

mode: daemonset
presets:
hostMetrics:
enabled: true

By default, the preset will scrape every 10 seconds, which may generate too many metrics for your backend system. Be aware of this and consider overriding it to 60 seconds. The following table also shows the metrics that will be scraped by default using the preset:

Metric ScraperDescriptionIncluded when using the hostMetrics preset
CPUScrapes CPU utilization metricsYes
DiskScrapes disk I/O metricsYes
LoadScrapes CPU load metricsYes
FilesystemScrapes filesystem utilization metricsYes
MemoryScrapes memory utilization metricsYes
NetworkScrapes network interface I/O metrics and TCP connection metricsYes
PagingScrapes paging and swap space utilization and I/O metricsNo
ProcessesScrapes process count metricsNo
ProcessScrapes per-process CPU, memory, and disk I/O metricsNo

Table 7.2 – Host Metrics Receiver scrapers

Let’s now take a look at our first cloud provider, AWS, and the connectivity options available.

Visualizing AWS telemetry with Grafana Cloud

Section titled “Visualizing AWS telemetry with Grafana Cloud”

There are two main ways in which you can visualize your AWS telemetry with Grafana Cloud:

  • Amazon CloudWatch data source: Amazon CloudWatch telemetry remains in AWS and Grafana is configured to remotely read the data at query time
  • AWS integration: AWS CloudWatch telemetry data is either sent to or scraped and stored in Grafana Cloud (logs in Loki and metrics in Mimir).

Let’s take a look at the differences between these two options to understand whether the integration option or the data source option best fits your use case.

Grafana Cloud comes with support for Amazon CloudWatch, allowing you to query, trigger alerts, and visualize your data in Grafana dashboards. To read CloudWatch telemetry, you will need to configure the AWS Identity and Access Management (IAM) permissions and provide the necessary authentication details in the data source configuration screen. This does not store any telemetry data in Grafana; it only retrieves it at query time.

Let’s now look at the different configuration steps.

Data sources can be accessed from the menu under the Connections item. To create a new connection, click the Add new data source button and search for CloudWatch. For existing ones, search for CloudWatch in the Data sources search box. You will see a screen similar to the following. Click CloudWatch to open the Settings page:

Figure 7.1 – Grafana Connections Data sources screen

The Settings screen requires the AWS configuration details needed to establish the connection, as shown in the following screenshot. Here, you can also configure namespace details for custom metrics, log query timeouts, and X-Ray trace links:

Figure 7.2 – Amazon CloudWatch data source settings

The CloudWatch data source comes with its own specialized query editor that can query data from both CloudWatch metrics and logs.

From the data explorer, you can select CloudWatch Metrics or CloudWatch Logs as the source data, as shown in the following screenshot:

Figure 7.3 – Amazon CloudWatch query editor

With the metrics editor in Builder mode, you can create a valid metric search query by specifying the namespace, metric name, and at least one statistic.

The logs editor provides a Log group selector, allowing you to specify the target log groups and then use AWS CloudWatch Logs Query Language https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html in the query editor.

On the data source Settings screen, there is a Dashboards tab with a set of pre-configured dashboards to get you started.

The following figure shows the list of available dashboards and import details (if a dashboard has already been imported, you will see the options to delete or reimport):

Figure 7.4 – Amazon CloudWatch pre-configured dashboards

Let’s now take a look at the AWS integration option.

The AWS integration option can be added to your account. It will then be available as a connection. When added and configured, you will be able to ingest metric and log data directly into Grafana, which provides a query time benefit as the data is contained within your Grafana Cloud stack. The metrics and logs can then be queried using LogQL or PromQL; see Chapter 4 and Chapter 5 for refreshers.

Let’s now look at the different configuration steps.

The AWS connection can be accessed from the menu under the Connections item. Search for aws from the Add new connection screen; you will see a screen similar to the following. You will see this is an Infrastructure connection and is labeled as Guide. This means there will be comprehensive instructions to help you connect the account and walk you through the process:

Figure 7.5 – Grafana Add new connection screen

Selecting the AWS integration option presents you with several options for integration – CloudWatch metrics, Logs with Lambda, and Logs with Firehose – as shown in the following screenshot:

Figure 7.6 – AWS integration screen

Next, we will discuss CloudWatch metrics and Logs with Lambda.

The CloudWatch integration allows you to scrape Amazon CloudWatch metrics without installing any collector or agent infrastructure. Multiple scrape jobs can be created to separate concerns, but metrics can only be discovered for AWS resources with tags.

As mentioned earlier, this integration is guided and presents you with all the necessary details to get started by using infrastructure as code or by manually connecting and configuring scrape jobs. The following screenshot shows the CloudWatch metrics Configuration Details screen:

Figure 7.7 – CloudWatch Configuration Details screen

Additionaly there are some pre-built dashboards that are ready to use. The following figure shows the list of pre-built dashboards that come with the integration option at the time of writing:

Figure 7.8 – Sample CloudWatch Metrics dashboard

The Logs with Lambda integration enables you to send CloudWatch logs to Grafana Cloud. The integration will guide you through the deployment of an AWS Lambda function that forwards CloudWatch logs to Grafana Cloud Loki, where they can be queried using LogQL. Chapter 4 explains Loki and LogQL in detail.

The following screenshot shows the Logs with Lambda configuration screen where you can select your deployment approach:

Figure 7.9 – Logs with Lambda configuration details

The following screenshot shows the configuration steps as the onscreen guide walks you through the connection and configuration of the logs integration:

Figure 7.10 – Logs with Lambda CloudFormation configuration

Let’s now look at our second cloud provider – GCP.

Grafana Cloud comes with support for Google Cloud Monitoring, allowing you to query, trigger alerts, and visualize your data in Grafana dashboards. It does not store any telemetry data in Grafana; it only retrieves it at query time.

Let’s now look at the steps for configuring the data source.

Data sources can be accessed from the menu under the Connections item. Search for Google Cloud Monitoring in the Data sources search box; you will see a screen similar to the one shown in Figure 7*.11*. Click on Google Cloud Monitoring to open the settings page. The settings screen prompts for the Google configuration needed to establish and test the connection. The Connections search results screen is shown here:

Figure 7.11 – Connections search results screen

The configuration settings for Google Cloud Monitoring shown in the following screenshot walk you through the configuration, helping you to choose an authentication method of either JSON Web Token (JWT) or GCE Default Service Account:

Figure 7.12 – Google Cloud Monitoring configuration settings

Depending upon the size of your GCP deployment, you may have to consider, as part of your design, any limits imposed on the token or service account.

The Google Cloud Monitoring data source comes with its own specialized query editor that can help you build queries for metrics and GCP Service Level Objectives (SLOs), both of which return time-series data (you will learn more about visualizing time-series data in Chapter 8). Metrics can be queried using the Builder interface or using GCP’s Monitoring Query Language (MQL). The SLO query builder helps you visualize SLO data in a time-series format. To understand the basic concepts of GCP service monitoring, refer to the GCP documentation at https://cloud.google.com/stackdriver/docs/solutions/slo-monitoring.

The Google Cloud Monitoring query editor in the following screenshot shows the three available choices:

Figure 7.13 – Google Cloud Monitoring query editor selection

Let’s look at the different Explorer query types:

  • Metrics queries: The metrics query editor builder helps you select metrics, group and aggregate them by labels and time, and specify time filters for the time-series data you want to query:

Figure 7.14 – Google Cloud Monitoring query editor metrics builder

The following screenshot shows the query editor for MQL, which provides an interface to create and execute your MQL query:

Figure 7.15 – Google Cloud Monitoring query editor metrics MQL interface

Full documentation for the MQL language specification can be found on the Google Cloud website at https://cloud.google.com/monitoring/mql.

  • SLO queries: The SLO query builder helps you visualize SLO data in time-series format. Documentation to explain the basic concepts of service monitoring can be found on the Google Cloud website at https://cloud.google.com/stackdriver/docs/solutions/slo-monitoring. The Google Cloud Monitoring SLO query editor is shown in the following screenshot:

Figure 7.16 – Google Cloud Monitoring query editor metrics SLO builder

From the Data source | Settings screen, the Dashboards tab lists a set of pre-configured dashboards to get you started. The following screenshot shows the list of available dashboards at the time of writing and import details (if a dashboard has already been imported, there are options to delete or reimport). You can see from the list the various GCP components that are covered, including firewalls, data processing, SQL, and so on:

Figure 7.17 – Google Cloud Monitoring pre-built dashboards

Let’s now look at our third cloud provider, Azure.

Grafana Cloud comes with support for Azure, allowing you to query, trigger alerts, and visualize your data in Grafana dashboards. This is called the Azure Monitor data source. As with the other cloud data sources, it does not store any telemetry data in Grafana; it only retrieves it at query time.

Let’s now step through the configuration.

Data sources can be accessed from the menu under the Connections item. Search for Azure Monitor in the Data sources search box; you will see a screen similar to the following:

Figure 7.18 – Connection search results screen for Azure Monitor

Click on Azure Monitor to open the settings page. The configuration settings for Azure Monitor shown in the following screenshot walk you through the configuration, helping you to set up authentication using the Azure Client Secret configuration, and test the connection:

Figure 7.19 – Azure Monitor data source settings screen

The Azure Monitor data source comes with its own specialized query editor that can help you build queries for metrics and logs, Azure Resource Graph, and Application Insights traces.

The following Azure Monitor query editor screenshot shows four choices:

Figure 7.20 – Azure Monitor query editor selector

Let’s look at these options in detail:

  • Metrics queries: The Azure Monitor metrics queries collect numeric data from Azure-supported resources, which are listed here on the Microsoft Azure website: https://learn.microsoft.com/en-us/azure/azure-monitor/monitor-reference. The metrics store numeric data only, and in a specific structure that allows for near real-time detection of platform health, performance, and usage. The Azure Monitor metrics query builder is shown here:

Figure 7.21 – Azure Monitor metrics query builder

  • Log queries: The Azure Monitor logs queries collect and organize log data from Azure-supported resources. A variety of data types, each with their own defined structure, are accessible, and to access these, the Kusto Query Language (KQL) can be used. An overview of KQL can be found on the Microsoft Azure website here: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/. The Azure Monitor logs query editor is shown in the following screenshot:

Figure 7.22 – Azure Monitor logs query editor

Azure Monitor logs can store a variety of data types, each with its own structure. For more details, you can refer to https://learn.microsoft.com/en-us/azure/azure-monitor/monitor-reference.

  • Traces queries: The Azure Monitor traces queries can be regarded as Azure Application Insights under the hood. The Azure Application Insights service provides application performance monitoring (APM) features to its workloads. The Azure Monitor traces can be used to interrogate and visualize various metrics and trace data. The query editor looks like this:

Figure 7.23 – Azure Monitor traces query editor

  • Azure Resource Graph (ARG): The ARG service extends the functionality of Azure Resource Manager by providing the ability to query across multiple Azure subscriptions in a scalable manner. This allows you to query Azure resources using the resource graph query language, making it ideal for querying and analyzing larger Azure cloud infrastructure deployments. Full documentation for the resource graph query language can be found at https://learn.microsoft.com/en-us/azure/governance/resource-graph/samples/starter?tabs=azure-cli. The following example query shows all resources by name:
    Resources | project name, type, location | order by name asc
    Here’s what the ARG query editor looks like:

Figure 7.24 – Azure Resource Graph query editor

From the Data source | Settings screen, the Dashboards tab shows a set of pre-configured dashboards that will get you started with Azure Monitor. In the following screenshot, there is a list of the various Azure components that have dashboards designed for them; they include applications, SQL servers, and storage accounts:

Figure 7.25 – Azure Monitor pre-built dashboards

Let’s now review some of the best practices we have covered for each of the cloud infrastructure providers we have discussed in this chapter.

In this chapter, we have provided an overview of several popular cloud infrastructures. Let’s now discuss some of the best practices that should be considered when implementing observability on any application or system:

  • Performance: The process of retrieving telemetry data can potentially incur a performance overhead. For example, with a remote Grafana data source, the telemetry data is fetched at query time over a great distance. This can introduce latency when compared to data stored closer to the Grafana query engine using one of the Grafana Cloud data sources, such as Loki, Mimir, and Tempo. Where performance is important and there is an option to ship telemetry into Grafana, that could be the best choice. Alternatively, several data sources have caching options to improve query speed; improvements in query speed can also be made using specific configurations. Take the time to understand your data and ensure you are using it in an optimal way.
  • Cost: Alongside the increased network and storage costs of shipping data into Grafana Cloud, there can also be costs when querying a cloud provider API. It is important to understand where charges are raised. This ensures that they are factored in when you’re designing your observability solution for the specific platform that your systems utilize.
  • Constraints: In general, infrastructure platforms come configured with constraints in place to protect the system. Sometimes these are soft limits that can be relaxed after careful consideration, but they may be hard limits. Before committing to a solution for a specific platform, understand your requirements and the volume of data or query transactions expected. You can compare these to any documented limits, your API key use, or your network egress volumes, therefore validating that the system will support your needs.
  • Security: For most of the configuration options we discussed in this chapter, we identified how they can be set up to generate separation of concerns. Having separate data sources or other controls on the data being queried or ingested will allow you to improve your security posture based on the underlying data and use case.

Important note

As this book was nearing publication, Grafana Labs released private data source connect (PDC), which gives administrators the ability to connect to any network-secured data source, regardless of where it is hosted. We have not covered this topic, but it is likely to be of interest to readers.

We will now wrap this chapter up with a summary and set the stage for the next chapter.

In this chapter, we have looked at various common cloud infrastructure providers, starting with Kubernetes, and we presented examples that can be used with the demo project provided alongside this book. We then looked at the big three cloud providers, AWS, GCP, and Azure. We presented an overview of the connection options and how to get started with the pre-built dashboards and the data explorer. Lastly, we covered some of the best practices that need to be considered with all observability integrations.

In the next chapter, we move on from getting telemetry data into Grafana and on to the visualization of that data using dashboards. This is where the fun starts!