One place for hosting & domains

      Grafana

      How to Deploy Prometheus Operator and Grafana on Linode Kubernetes Engine


      Updated by Linode Written by Ben Bigger

      In this guide, you will deploy the Prometheus Operator to your Linode Kubernetes Engine (LKE) cluster using Helm, either as:

      The Prometheus Operator Monitoring Stack

      When administrating any system, effective monitoring tools can empower users to perform quick and effective issue diagnosis and resolution. This need for monitoring solutions has led to the development of several prominent open source tools designed to solve problems associated with monitoring diverse systems.

      Since its release in 2016, Prometheus has become a leading monitoring tool for containerized environments including Kubernetes. Alertmanager is often used with Prometheus to send and manage alerts with tools such as Slack. Grafana, an open source visualization tool with a robust web interface, is commonly deployed along with Prometheus to provide centralized visualization of system metrics.

      The community-supported Prometheus Operator Helm Chart provides a complete monitoring stack including each of these tools along with Node Exporter and kube-state-metrics, and is designed to provide robust Kubernetes monitoring in its default configuration.

      While there are several options for deploying the Prometheus Operator, using Helm, a Kubernetes “package manager,” to deploy the community-supported the Prometheus Operator enables you to:

      • Control the components of your monitoring stack with a single configuration file.
      • Easily manage and upgrade your deployments.
      • Utilize out-of-the-box Grafana interfaces built for Kubernetes monitoring.

      Before You Begin

      Note

      1. Deploy an LKE Cluster. This guide was written using an example node pool with three 2 GB Linodes. Depending on the workloads you will be deploying on your cluster, you may consider using Linodes with more available resources.

      2. Install Helm 3 to your local environment.

      3. Install kubectl to your local environment and connect to your cluster.

      4. Create the monitoring namespace on your LKE cluster:

        kubectl create namespace monitoring
        
      5. Create a directory named lke-monitor to store all of your Helm values and Kubernetes manifest files and move into the new directory:

        mkdir ~/lke-monitor && cd ~/lke-monitor
        
      6. Add the Google stable Helm charts repository to your Helm repos:

        helm repo add stable https://kubernetes-charts.storage.googleapis.com/
        
      7. Update your Helm repositories:

        helm repo update
        
      8. (Optional) For public access with HTTPS and basic auth configured for your web interfaces of your monitoring tools:

        • Purchase a domain name from a reliable domain registrar and configure your registrar to use Linode’s nameservers with your domain. Using Linode’s DNS Manager, create a new Domain for the one that you have purchased.

        • Ensure that htpasswd is installed to your local environment. For many systems, this tool has already been installed. Debian and Ubuntu users will have to install the apache2-utils package with the following command:

          sudo apt install apache2-utils
          

      Prometheus Operator Minimal Deployment

      In this section, you will complete a minimal deployment of the Prometheus Operator for individual/local access with kubectl Port-Forward. If you require your monitoring interfaces to be publicly accessible over the internet, you can skip to the following section on completing a Prometheus Operator Deployment with HTTPS and Basic Auth.

      Deploy Prometheus Operator

      In this section, you will create a Helm chart values file and use it to deploy Prometheus Operator to your LKE cluster.

      1. Using the text editor of your choice, create a file named values.yaml in the ~/lke-monitor directory and save it with the configurations below. Since the control plane is Linode-managed, as part of this step we will also disable metrics collection for the control plane component:

        Caution

        The below configuration will establish persistent data storage with three separate 10GiB Block Storage Volumes for Prometheus, Alertmanager, and Grafana. Because the Prometheus Operator deploys as StatefulSets, these Volumes and their associated Persistent Volume resources must be deleted manually if you later decide to tear down this Helm release.
        ~/lke-monitor/values.yaml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        
        # Prometheus Operator Helm Chart values for Linode Kubernetes Engine minimal deployment
        prometheus:
          prometheusSpec:
            storageSpec:
              volumeClaimTemplate:
                spec:
                  storageClassName: linode-block-storage-retain
                  resources:
                    requests:
                      storage: 10Gi
        
        alertmanager:
          alertmanagerSpec:
            storage:
              volumeClaimTemplate:
                spec:
                  storageClassName: linode-block-storage-retain
                  resources:
                    requests:
                      storage: 10Gi
        
        grafana:
          persistence:
            enabled: true
            storageClassName: linode-block-storage-retain
            size: 10Gi
        
        # Disable metrics for Linode-managed Kubernetes control plane elements
        kubeEtcd:
          enabled: false
        
        kubeControllerManager:
          enabled: false
        
        kubeScheduler:
          enabled: false
            
      2. Export an environment variable to store your Grafana admin password:

        Note

        Replace prom-operator in the below command with a secure password and save the password for later reference.

        export GRAFANA_ADMINPASSWORD="prom-operator"
        
      3. Using Helm, deploy a Prometheus Operator release labeled lke-monitor in the monitoring namespace on your LKE cluster with the settings established in your values.yaml file:

        helm install 
        lke-monitor stable/prometheus-operator 
        -f ~/lke-monitor/values.yaml 
        --namespace monitoring 
        --set grafana.adminPassword=$GRAFANA_ADMINPASSWORD 
        --set prometheusOperator.createCustomResource=false
        

        Note

        You can safely ignore messages similar to manifest_sorter.go:192: info: skipping unknown hook: "crd-install" as discussed in this Github issues thread.

        Alternatively, you can add --set prometheusOperator.createCustomResource=false to the above command to prevent the message from appearing.

      4. Verify that the Prometheus Operator has been deployed to your LKE cluster and its components are running and ready by checking the pods in the monitoring namespace:

        kubectl -n monitoring get pods
        

        You should see a similar output to the following:

          
        NAME                                                     READY   STATUS    RESTARTS   AGE
        alertmanager-lke-monitor-prometheus-ope-alertmanager-0   2/2     Running   0          45s
        lke-monitor-grafana-84cbb54f98-7gqtk                     2/2     Running   0          54s
        lke-monitor-kube-state-metrics-68c56d976f-n587d          1/1     Running   0          54s
        lke-monitor-prometheus-node-exporter-6xt8m               1/1     Running   0          53s
        lke-monitor-prometheus-node-exporter-dkc27               1/1     Running   0          53s
        lke-monitor-prometheus-node-exporter-pkc65               1/1     Running   0          53s
        lke-monitor-prometheus-ope-operator-f87bc9f7c-w56sw      2/2     Running   0          54s
        prometheus-lke-monitor-prometheus-ope-prometheus-0       3/3     Running   1          35s
            
        

      Access Monitoring Interfaces with Port-Forward

      1. List the services running in the monitoring namespace and review their respective ports:

        kubectl -n monitoring get svc
        

        You should see an output similar to the following:

          
        NAME                                      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)                     AGE
        alertmanager-operated                     ClusterIP   None            <none>        9093/TCP,9094/TCP,9094/UDP  115s
        lke-monitor-grafana                       ClusterIP   10.128.140.155  <none>        80/TCP                      2m3s
        lke-monitor-kube-state-metrics            ClusterIP   10.128.165.34   <none>        8080/TCP                    2m3s
        lke-monitor-prometheus-node-exporter      ClusterIP   10.128.192.213  <none>        9100/TCP                    2m3s
        lke-monitor-prometheus-ope-alertmanager   ClusterIP   10.128.153.6    <none>        9093/TCP                    2m3s
        lke-monitor-prometheus-ope-operator       ClusterIP   10.128.198.160  <none>        8080/TCP,443/TCP            2m3s
        lke-monitor-prometheus-ope-prometheus     ClusterIP   10.128.121.47   <none>        9090/TCP                    2m3s
        prometheus-operated                       ClusterIP   None            <none>        9090/TCP                    105s
            
        

        From the above output, the resource services you will access have the corresponding ports:

        ResourceService NamePort
        Prometheuslke‑monitor‑prometheus‑ope‑prometheus9090
        Alertmanagerlke‑monitor‑prometheus‑ope‑alertmanager9093
        Grafanalke‑monitor‑grafana80
      2. Use kubectl port-forward to open a connection to a service, then access the service’s interface by entering the corresponding address in your web browser:

        Note

        Press control+C on your keyboard to terminate a port-forward process after entering any of the following commands.

        • To provide access to the Prometheus interface at the address 127.0.0.1:9090 in your web browser, enter:

          kubectl -n monitoring 
          port-forward 
          svc/lke-monitor-prometheus-ope-prometheus 
          9090
          
        • To provide access to the Alertmanager interface at the address 127.0.0.1:9093 in your web browser, enter:

          kubectl -n monitoring 
          port-forward 
          svc/lke-monitor-prometheus-ope-alertmanager  
          9093
          
        • To provide access to the Grafana interface at the address 127.0.0.1:8081 in your web browser, enter:

          kubectl -n monitoring 
          port-forward 
          svc/lke-monitor-grafana  
          8081:80
          

          Log in with the username admin and the password you exported as $GRAFANA_ADMINPASSWORD. The Grafana dashboards are accessible at Dashboards > Manage from the left navigation bar.

      Prometheus Operator Deployment with HTTPS and Basic Auth

      Note

      Before you start on this section, ensure that you have completed all of the steps in Before you Begin.

      This section will show you how to install and configure the necessary components for secure, path-based, public access to the Prometheus, Alertmanager, and Grafana interfaces using the domain you have configured for use with Linode.

      An Ingress is used to provide external routes, via HTTP or HTTPS, to your cluster’s services. An Ingress Controller, like the NGINX Ingress Controller, fulfills the requirements presented by the Ingress using a load balancer.

      To enable HTTPS on your monitoring interfaces, you will create a Transport Layer Security (TLS) certificate from the Let’s Encrypt certificate authority (CA) using the ACME protocol. This will be facilitated by cert-manager, the native Kubernetes certificate management controller.

      While the Grafana interface is natively password-protected, the Prometheus and Alertmanager interfaces must be secured by other means. This guide covers basic authentication configurations to secure the Prometheus and Alertmanager interfaces.

      If you are completing this section of the guide after completing a Prometheus Operator Minimal Deployment, you can use Helm to upgrade your release and maintain the persistent data storage for your monitoring stack.

      Install the NGINX Ingress Controller

      In this section, you will install the NGINX Ingress Controller using Helm, which will create a NodeBalancer to handle your cluster’s traffic.

      1. Install the Google stable NGINX Ingress Controller Helm chart:

        helm install nginx-ingress stable/nginx-ingress
        
      2. Access your NodeBalancer’s assigned external IP address.

        kubectl -n default get svc -o wide nginx-ingress-controller
        

        The command will return a similar output to the following:

          
        NAME                       TYPE           CLUSTER-IP      EXTERNAL-IP    PORT(S)                      AGE   SELECTOR
        nginx-ingress-controller   LoadBalancer   10.128.41.200   192.0.2.0      80:30889/TCP,443:32300/TCP   59s   app.kubernetes.io/component=controller,app=nginx-ingress,release=nginx-ingress
            
        
      3. Copy the IP address of the EXTERNAL IP field and navigate to Linode’s DNS Manager and create an A record using this external IP address and a hostname value corresponding to the subdomain you plan to use with your domain.

      Now that your NGINX Ingress Controller has been deployed and your domain’s A record has been updated, you are ready to enable HTTPS on your monitoring interfaces.

      Install cert-manager

      Note

      Before performing the commands in this section, ensure that your DNS has had time to propagate across the internet. You can query the status of your DNS by using the following command, substituting example.com for your domain (including a subdomain if you have configured one).

      dig +short example.com
      

      If successful, the output should return the IP address of your NodeBalancer.

      1. Install cert-manager’s CRDs.

        kubectl apply --validate=false -f https://github.com/jetstack/cert-manager/releases/download/v0.15.2/cert-manager.crds.yaml
        
      2. Add the Helm repository which contains the cert-manager Helm chart.

        helm repo add jetstack https://charts.jetstack.io
        
      3. Update your Helm repositories.

        helm repo update
        
      4. Install the cert-manager Helm chart. These basic configurations should be sufficient for many use cases, however, additional cert-manager configurable parameters can be found in cert-manager’s official documentation.

        helm install 
        cert-manager jetstack/cert-manager 
        --namespace cert-manager 
        --version v0.15.2
        
      5. Verify that the corresponding cert-manager pods are running and ready.

        kubectl -n cert-manager get pods
        

        You should see a similar output:

          
        NAME                                       READY   STATUS    RESTARTS   AGE
        cert-manager-749df5b4f8-mc9nj              1/1     Running   0          19s
        cert-manager-cainjector-67b7c65dff-4fkrw   1/1     Running   0          19s
        cert-manager-webhook-7d5d8f856b-4nw9z      1/1     Running   0          19s
            
        

      Create a ClusterIssuer Resource

      Now that cert-manager is installed and running on your cluster, you will need to create a ClusterIssuer resource which defines which CA can create signed certificates when a certificate request is received. A ClusterIssuer is not a namespaced resource, so it can be used by more than one namespace.

      1. Using the text editor of your choice, create a file named acme-issuer-prod.yaml with the example configurations, replacing the value of email with your own email address for the ACME challenge:

        ~/lke-monitor/acme-issuer-prod.yaml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        
        apiVersion: cert-manager.io/v1alpha2
        kind: ClusterIssuer
        metadata:
          name: letsencrypt-prod
        spec:
          acme:
            email: [email protected]
            server: https://acme-v02.api.letsencrypt.org/directory
            privateKeySecretRef:
              name: letsencrypt-secret-prod
            solvers:
            - http01:
                ingress:
                  class: nginx
            
        • This manifest file creates a ClusterIssuer resource that will register an account on an ACME server. The value of spec.acme.server designates Let’s Encrypt’s production ACME server, which should be trusted by most browsers.

          Note

          Let’s Encrypt provides a staging ACME server that can be used to test issuing trusted certificates, while not worrying about hitting Let’s Encrypt’s production rate limits. The staging URL is https://acme-staging-v02.api.letsencrypt.org/directory.
        • The value of privateKeySecretRef.name provides the name of a secret containing the private key for this user’s ACME server account (this is tied to the email address you provide in the manifest file). The ACME server will use this key to identify you.

        • To ensure that you own the domain for which you will create a certificate, the ACME server will issue a challenge to a client. cert-manager provides two options for solving challenges, http01 and DNS01. In this example, the http01 challenge solver will be used and it is configured in the solvers array. cert-manager will spin up challenge solver Pods to solve the issued challenges and use Ingress resources to route the challenge to the appropriate Pod.

      2. Create the ClusterIssuer resource:

        kubectl apply -f ~/lke-monitor/acme-issuer-prod.yaml
        

      Create a Certificate Resource

      After you have a ClusterIssuer resource, you can create a Certificate resource. This will describe your x509 public key certificate and will be used to automatically generate a CertificateRequest which will be sent to your ClusterIssuer.

      1. Using the text editor of your choice, create a file named certificate-prod.yaml with the example configurations:

        Note

        Replace the value of spec.dnsNames with the domain, including subdomains, that you will use to host your monitoring interfaces.

        ~/lke-monitor/certificate-prod.yaml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        
        apiVersion: cert-manager.io/v1alpha2
        kind: Certificate
        metadata:
          name: prometheus-operator-prod
          namespace: monitoring
        spec:
          secretName: letsencrypt-secret-prod
          duration: 2160h # 90d
          renewBefore: 360h # 15d
          issuerRef:
            name: letsencrypt-prod
            kind: ClusterIssuer
          dnsNames:
          - example.com
            

        Note

        The configurations in this example create a Certificate in the monitoring namespace that is valid for 90 days and renews 15 days before expiry.

      2. Create the Certificate resource:

        kubectl apply -f ~/lke-monitor/certificate-prod.yaml
        
      3. Verify that the Certificate has been successfully issued:

        kubectl -n monitoring get certs
        

        When your certificate is ready, you should see a similar output:

          
        NAME          READY   SECRET                    AGE
        lke-monitor   True    letsencrypt-secret-prod   33s
            
        

      Next, you will create the necessary resources for basic authentication of the Prometheus and Alertmanager interfaces.

      Configure Basic Auth Credentials

      In this section, you will use htpasswd to generate credentials for basic authentication and create a Kubernetes Secret, which will then be applied to your Ingress configuration to secure access to your monitoring interfaces.

      1. Create a basic authentication password file for the user admin:

        htpasswd -c ~/lke-monitor/auth admin
        

        Follow the prompts to create a secure password, then store your password securely for future reference.

      2. Create a Kubernetes Secret for the monitoring namespace using the file you created above:

        kubectl -n monitoring create secret generic basic-auth --from-file=auth
        
      3. Verify that the basic-auth secret has been created on your LKE cluster:

        kubectl -n monitoring get secret basic-auth
        

        You should see a similar output to the following:

          
        NAME         TYPE     DATA   AGE
        basic-auth   Opaque   1      81s
            
        

      All the necessary components are now in place to be able to enable HTTPS on your monitoring interfaces. In the next section, you will complete the steps needed to deploy Prometheus Operator.

      Deploy or Upgrade Prometheus Operator

      In this section, you will create a Helm chart values file and use it to deploy Prometheus Operator to your LKE cluster.

      1. Using the text editor of your choice, create a file named values-https-basic-auth.yaml in the ~/lke-monitor directory and save it with the configurations below. Since the control plane is Linode-managed, as part of this step we will also disable metrics collection for the control plane component:

        Note

        Caution

        The below configuration will establish persistent data storage with three separate 10GiB Block Storage Volumes for Prometheus, Alertmanager, and Grafana. Because the Prometheus Operator deploys as StatefulSets, these Volumes and their associated Persistent Volume resources must be deleted manually if you later decide to tear down this Helm release.
        ~/lke-monitor/values-https-basic-auth.yaml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        68
        69
        70
        71
        72
        73
        74
        75
        76
        77
        78
        79
        80
        81
        82
        83
        84
        85
        86
        87
        88
        89
        90
        91
        92
        93
        94
        95
        
        # Helm chart values for Prometheus Operator with HTTPS and basic auth
        prometheus:
          ingress:
            enabled: true
            annotations:
              kubernetes.io/ingress.class: nginx
              nginx.ingress.kubernetes.io/rewrite-target: /$2
              cert-manager.io/cluster-issuer: letsencrypt-prod
              nginx.ingress.kubernetes.io/auth-type: basic
              nginx.ingress.kubernetes.io/auth-secret: basic-auth
              nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required'
            hosts:
            - example.com
            paths:
            - /prometheus(/|$)(.*)
            tls:
            - secretName: lke-monitor-tls
              hosts:
              - example.com
          prometheusSpec:
            routePrefix: /
            externalUrl: https://example.com/prometheus
            storageSpec:
              volumeClaimTemplate:
                spec:
                  storageClassName: linode-block-storage-retain
                  resources:
                    requests:
                      storage: 10Gi
        
        alertmanager:
          ingress:
            enabled: true
            annotations:
              kubernetes.io/ingress.class: nginx
              nginx.ingress.kubernetes.io/rewrite-target: /$2
              cert-manager.io/cluster-issuer: letsencrypt-prod
              nginx.ingress.kubernetes.io/auth-type: basic
              nginx.ingress.kubernetes.io/auth-secret: basic-auth
              nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required'
            hosts:
            - example.com
            paths:
            - /alertmanager(/|$)(.*)
            tls:
            - secretName: lke-monitor-tls
              hosts:
              - example.com
          alertmanagerSpec:
            routePrefix: /
            externalUrl: https://example.com/alertmanager
            storage:
              volumeClaimTemplate:
                spec:
                  storageClassName: linode-block-storage-retain
                  resources:
                    requests:
                      storage: 10Gi
        
        grafana:
          persistence:
            enabled: true
            storageClassName: linode-block-storage-retain
            size: 10Gi
          ingress:
            enabled: true
            annotations:
              kubernetes.io/ingress.class: nginx
              nginx.ingress.kubernetes.io/rewrite-target: /$2
              nginx.ingress.kubernetes.io/auth-type: basic
              nginx.ingress.kubernetes.io/auth-secret: basic-auth
              nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required'
            hosts:
            - example.com
            path: /grafana(/|$)(.*)
            tls:
            - secretName: lke-monitor-tls
              hosts:
              - example.com
          grafana.ini:
            server:
              domain: example.com
              root_url: "%(protocol)s://%(domain)s/grafana/"
              enable_gzip: "true"
        
        # Disable control plane metrics
        kubeEtcd:
          enabled: false
        
        kubeControllerManager:
          enabled: false
        
        kubeScheduler:
          enabled: false
            
      2. Export an environment variable to store your Grafana admin password:

        Note

        Replace prom-operator in the below command with a secure password and save the password for later reference.

        export GRAFANA_ADMINPASSWORD="prom-operator"
        
      3. Using Helm, deploy a Prometheus Operator release labeled lke-monitor in the monitoring namespace on your LKE cluster with the settings established in your values-https-basic-auth.yaml file:

        Note

        If you have already deployed a Prometheus Operator release, you can upgrade it by replacing helm install with helm upgrade in the below command.

        helm install 
        lke-monitor stable/prometheus-operator 
        -f ~/lke-monitor/values-https-basic-auth.yaml 
        --namespace monitoring 
        --set grafana.adminPassword=$GRAFANA_ADMINPASSWORD
        

        Once completed, you will see output similar to the following:

          
        NAME: lke-monitor
        LAST DEPLOYED: Mon Jul 27 17:03:46 2020
        NAMESPACE: monitoring
        STATUS: deployed
        REVISION: 1
        NOTES:
        The Prometheus Operator has been installed. Check its status by running:
          kubectl --namespace monitoring get pods -l "release=lke-monitor"
        
        Visit https://github.com/coreos/prometheus-operator for instructions on how
        to create & configure Alertmanager and Prometheus instances using the Operator.
        
        
      4. Verify that the Prometheus Operator has been deployed to your LKE cluster and its components are running and ready by checking the pods in the monitoring namespace:

        kubectl -n monitoring get pods
        

        You should see a similar output to the following, confirming that you are ready to access your monitoring interfaces using your domain:

          
        NAME                                                     READY   STATUS    RESTARTS   AGE
        alertmanager-lke-monitor-prometheus-ope-alertmanager-0   2/2     Running   0          45s
        lke-monitor-grafana-84cbb54f98-7gqtk                     2/2     Running   0          54s
        lke-monitor-kube-state-metrics-68c56d976f-n587d          1/1     Running   0          54s
        lke-monitor-prometheus-node-exporter-6xt8m               1/1     Running   0          53s
        lke-monitor-prometheus-node-exporter-dkc27               1/1     Running   0          53s
        lke-monitor-prometheus-node-exporter-pkc65               1/1     Running   0          53s
        lke-monitor-prometheus-ope-operator-f87bc9f7c-w56sw      2/2     Running   0          54s
        prometheus-lke-monitor-prometheus-ope-prometheus-0       3/3     Running   1          35s
            
        

      Access Monitoring Interfaces from your Domain

      Your monitoring interfaces are now publicly accessible with HTTPS and basic auth from the domain you have configured for use with this guide at the following paths:

      ResourceDomain and path
      Prometheusexample.com/prometheus
      Alertmanagerexample.com/alertmanager
      Grafanaexample.com/grafana

      When accessing an interface for the first time, log in as admin with the password you configured for basic auth credentials.

      When accessing the Grafana interface, you will then log in again as admin with the password you exported as $GRAFANA_ADMINPASSWORD on your local environment. The Grafana dashboards are accessible at Dashboards > Manage from the left navigation bar.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      Installieren und Sichern von Grafana unter Ubuntu 20.04


      Der Autor hat den COVID-19 Relief Fund dazu ausgewählt, eine Spende im Rahmen des Programms Write for DOnations zu erhalten.

      Einführung

      Grafana ist ein Open-Source-basiertes Visualisierungs- und Überwachungstool für Daten, das sich mit komplexen Daten aus Quellen wie Prometheus, InfluxDB, Graphite und ElasticSearch integrieren lässt. Mit Grafana können Sie Warnungen, Benachrichtigungen und Ad-hoc-Filter für Ihre Daten erstellen und durch integrierte Freigabefunktionen die Zusammenarbeit mit Teamkollegen erleichtern.

      In diesem Tutorial installieren Sie Grafana und sichern die Anwendung mit einem SSL-Zertifikat und einem Nginx-Reverseproxy. Nach der Einrichtung von Grafana haben Sie die Möglichkeit, Benutzerauthentifizierung über GitHub zu konfigurieren, um die Berechtigungen Ihres Teams besser zu organisieren.

      Voraussetzungen

      Um dieser Anleitung zu folgen, benötigen Sie:

      • Zwei Ubuntu 20.04-Server, die gemäß des Leitfadens zur Ersteinrichtung des Servers für Ubuntu 20.04 eingerichtet wurde, einschließlich eines non-root users, der über sudo-Berechtigungen verfügt, und einer mit ufw konfigurierten Firewall.
      • Einen vollständig registrierten Domänennamen. In diesem Tutorial wird durchgehend your_domain verwendet. Sie können einen Domänennamen unter Namecheap günstig erwerben oder einen kostenlosen von Freenom herunterladen oder einfach die Domänenregistrierungsstelle Ihrer Wahl verwenden.
      • Richten Sie die folgenden DNS-Einträge für Ihren Server ein. Sie können Einrichten eines Hostnamens mit DigitalOcean konsultieren, um mehr über das Hinzufügen von Hostnamen zu erfahren.
        • Einen A-Datensatz mit your-domain, der auf die öffentliche IP-Adresse Ihres Servers verweist.
        • Einen A-Eintrag mit www.your_domain, der auf die öffentliche IP-Adresse Ihres Servers verweist.
      • Nginx, eingerichtet anhand des Tutorials zum Installieren von Nginx unter Ubuntu 20.04, einschließlich eines Serverblocks für Ihre Domäne.
      • Einen Nginx-Serverblock mit konfiguriertem Let’s Encrypt; folgen Sie zum Einrichten dieser Komponente Sichern von Nginx mit Let’s Encrypt unter Ubuntu 20.04.
      • Optional benötigen Sie zur Einrichtung der GitHub-Authentifizierung ein GitHub-Konto, das mit einer Organisation verknüpft ist.

      Schritt 1 — Installieren von Grafana

      In diesem ersten Schritt installieren Sie Grafana auf Ihrem Ubuntu 20.04-Server. Sie können Grafana installieren, indem Sie entweder die Anwendung direkt von der offiziellen Website herunterladen oder ein APT-Repository verwenden. Da ein APT-Repository die Installation und Verwaltung von Grafana-Updates erleichtert, wenden wir in diesem Tutorial diese Methode an.

      Laden Sie mit wget den GPG-Schlüssel von Grafana herunter und übergeben Sie dann die Ausgabe an apt-key. Dadurch wird der Schlüssel zur Liste der vertrauenswürdigen Schlüssel Ihrer APT-Installation hinzugefügt. Nun können Sie das GPG-signierte Grafana-Paket herunterladen und verifizieren:

      • wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -

      In diesem Befehl deaktiviert die Option -q die Nachricht zur Statusaktualisierung für wget, während -O die Datei ausgibt, die Sie in das Terminal heruntergeladen haben. Diese beiden Optionen sorgen dafür, dass nur die Inhalte der heruntergeladenen Datei an apt-key übertragen werden.

      Fügen Sie als Nächstes das Grafana-Repository zu Ihren APT-Quellen hinzu:

      • sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main"

      Aktualisieren Sie dann den APT-Cache, um Ihre Paketlisten zu aktualisieren:

      Sie können nun mit der Installation fortfahren:

      Sobald Grafana installiert ist, verwenden Sie systemctl, um den Grafana-Server zu starten:

      • sudo systemctl start grafana-server

      Überprüfen Sie als Nächstes, ob Grafana ausgeführt wird, indem Sie den Status des Diensts prüfen:

      • sudo systemctl status grafana-server

      Sie erhalten eine ähnliche Ausgabe wie diese:

      Output

      ● grafana-server.service - Grafana instance Loaded: loaded (/lib/systemd/system/grafana-server.service; disabled; vendor preset: enabled) Active: active (running) since Thu 2020-05-21 08:08:10 UTC; 4s ago Docs: http://docs.grafana.org Main PID: 15982 (grafana-server) Tasks: 7 (limit: 1137) ...

      Diese Ausgabe enthält Informationen über den Prozess von Grafana, einschließlich seines Status, Main Process Identifier (PID) und mehr. active (running) bedeutet, dass der Prozess richtig ausgeführt wird.

      Abschließend aktivieren Sie den Dienst, damit Grafana beim Booten automatisch gestartet wird:

      • sudo systemctl enable grafana-server

      Sie erhalten die folgende Ausgabe:

      Output

      Synchronizing state of grafana-server.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable grafana-server Created symlink /etc/systemd/system/multi-user.target.wants/grafana-server.service → /usr/lib/systemd/system/grafana-server.service.

      Dadurch wird bestätigt, dass systemd die erforderlichen symbolischen Links für den Autostart von Grafana erstellt hat.

      Grafana ist nun installiert und einsatzbereit. Als Nächstes sichern Sie Ihre Verbindung zu Grafana mit einem Reverseproxy und SSL-Zertifikat.

      Schritt 2 — Einrichten des Reverseproxy

      Durch Verwendung eines SSL-Zertifikats wird sichergestellt, dass Ihre Daten sicher sind, indem die Verbindung zu und von Grafana verschlüsselt wird. Um diese Verbindung nutzen zu können, müssen Sie jedoch zunächst Nginx als Reverseproxy für Grafana neu konfigurieren.

      Öffnen Sie die Nginx-Konfigurationsdatei, die Sie beim Einrichten des Nginx-Serverblocks mit Let’s Encrypt in den Voraussetzungen erstellt haben. Sie können einen beliebigen Texteditor verwenden, für dieses Tutorial nutzen wir allerdings nano:

      • sudo nano /etc/nginx/sites-available/your_domain

      Suchen Sie nach dem folgenden Block:

      /etc/nginx/sites-available/your_domain

      ...
          location / {
              try_files $uri $uri/ =404;
          }
      ...
      

      Da Sie Nginx bereits für Kommunikation über SSL konfiguriert haben und der gesamte Webverkehr auf Ihrem Server schon über Nginx läuft, müssen Sie Nginx nur noch dazu anweisen, alle Anfragen an Grafana (standardmäßig an Port 3000) weiterzuleiten.

      Löschen Sie in diesem location block die vorhandene Zeile try_files und ersetzen Sie sie durch die folgende Option proxy_pass:

      /etc/nginx/sites-available/your_domain

      ...
          location / {
              proxy_pass http://localhost:3000;
          }
      ...
      

      Dadurch wird der Proxy dem entsprechenden Port zugeordnet. Sobald Sie damit fertig sind, speichern und schließen Sie die Datei, indem Sie STRG+X, Y und dann die Eingabetaste drücken (wenn Sie nano verwenden).

      Testen Sie nun die neuen Einstellungen, um sich zu vergewissern, dass alles korrekt konfiguriert wurde:

      Sie erhalten die folgende Ausgabe:

      Output

      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      Aktivieren Sie schließlich die Änderungen, indem Sie Nginx neu laden:

      • sudo systemctl reload nginx

      Sie können nun das Standardanmeldefenster von Grafana aufrufen, indem Sie in Ihren Webbrowser https://your_domain eingeben. Wenn Grafana nicht erreichbar ist, prüfen Sie, ob Ihre Firewall so eingerichtet ist, dass Datenverkehr an Port 443 zugelassen wird, und befolgen Sie dann erneut die vorherigen Anweisungen.

      Nachdem Sie die Verbindung zu Grafana verschlüsselt haben, können Sie nun zusätzliche Sicherheitsmaßnahmen implementieren, angefangen beim Ändern der standardmäßigen Anmeldedaten für den Grafana-Administrator.

      Schritt 3 — Aktualisieren von Anmeldedaten

      Da jede Grafana-Installation standardmäßig dieselben Administrator-Anmeldedaten nutzt, sollten Sie die Anmeldedaten so schnell wie möglich ändern. In diesem Schritt aktualisieren Sie die Anmeldedaten zur Verbesserung der Sicherheit.

      Navigieren Sie zunächst über Ihren Webbrowser zu https://your_domain. Dadurch wird das standardmäßige Anmeldefenster mit folgenden Elementen angezeigt: einem Formular, das Sie dazu auffordert, eine E-Mail-Adresse oder Benutzername und ein Passwort einzugeben, einer Schaltfläche zum Anmelden sowie einem Link namens Passwort vergessen? .

      Grafana-Anmeldung

      Geben Sie admin sowohl in das Feld E-Mail-Adresse oder Benutzername und Passwort ein und klicken Sie dann auf die Schaltfläche Anmelden.

      Im nächsten Fenster werden Sie aufgefordert, die Sicherheit Ihres Kontos zu erhöhen, indem Sie das Standardpasswort ändern:

      Passwort ändern

      Geben Sie das Passwort, das Sie verwenden möchten, in die Felder Neues Passwort und Neues Passwort bestätigen ein.

      Jetzt können Sie auf Übermitteln klicken, um die neuen Daten zu speichern, oder auf Überspringen, um diesen Schritt zu überspringen. Wenn Sie den Schritt überspringen, werden Sie dazu aufgefordert, das Passwort bei der nächsten Anmeldung zu ändern.

      Um die Sicherheit Ihrer Grafana-Konfiguration zu erhöhen, klicken Sie auf Übermitteln. Sie gelangen zum Dashboard Willkommen bei Grafana:

      Start-Dashboard

      Sie haben Ihr Konto sicherer gemacht, indem Sie die Standardanmeldedaten geändert haben. Als Nächstes werden Sie Änderungen an Ihrer Grafana-Konfiguration vornehmen, damit ohne Ihre Genehmigung niemand ein neues Grafana-Konto erstellen kann.

      Schritt 4 — Deaktivieren von Grafana-Registrierungen und anonymem Zugriff

      Grafana bietet Optionen, mit denen Besucher für sich selbst Benutzerkonten erstellen und eine Vorschau von Dashboards anzeigen können, ohne sich registrieren zu müssen. Wenn Grafana nicht über das Internet zugänglich ist oder mit öffentlich verfügbaren Daten wie Dienststatus arbeitet, können Sie diese Funktionen ggf. zulassen. Wenn Sie Grafana jedoch online verwenden, um mit sensiblen Daten zu arbeiten, kann anonymer Zugriff ein Sicherheitsproblem darstellen. Um dieses Problem zu beheben, nehmen Sie einige Änderungen an Ihrer Grafana-Konfiguration vor.

      Öffnen Sie zunächst die Hauptkonfigurationsdatei von Grafana zur Bearbeitung:

      • sudo nano /etc/grafana/grafana.ini

      Suchen Sie die folgende Direktive allow_sign_up unter der Überschrift [users]:

      /etc/grafana/grafana.ini

      ...
      [users]
      # disable user signup / registration
      ;allow_sign_up = true
      ...
      

      Wenn Sie diese Direktive mit true aktivieren, wird dem Anmeldefenster eine Schaltfläche zum Anmelden hinzugefügt, damit sich Benutzer registrieren und auf Grafana zugreifen können.

      Durch Deaktivieren dieser Direktive mit false wird die Schaltfläche zum Anmelden entfernt, was die Sicherheit und den Datenschutz von Grafana erhöht.

      Heben Sie die Kommentierung dieser Direktive auf, indem Sie das ;-Zeichen am Anfang der Zeile entfernen und dann die Option auf false setzen:

      /etc/grafana/grafana.ini

      ...
      [users]
      # disable user signup / registration
      allow_sign_up = false
      ...
      

      Als Nächstes suchen Sie nach der folgenden aktivierten Direktive unter der Überschrift [auth.anonymous]:

      /etc/grafana/grafana.ini

      ...
      [auth.anonymous]
      # enable anonymous access
      ;enabled = false
      ...
      

      Wenn Sie enabled auf true setzen, erhalten nicht registrierte Benutzer Zugriff auf Ihre Dashboards; wenn Sie die Option auf false setzen, wird der Zugriff auf das Dashboard auf registrierte Benutzer beschränkt.

      Heben Sie die Kommentierung dieser Direktive auf, indem Sie das ;-Zeichen am Anfang der Zeile entfernen und die Option dann auf false setzen:

      /etc/grafana/grafana.ini

      ...
      [auth.anonymous]
      # enable anonymous access
      enabled = false
      ...
      

      Speichern Sie die Datei und beenden Sie den Texteditor.

      Um die Änderungen zu aktivieren, starten Sie Grafana neu:

      • sudo systemctl restart grafana-server

      Vergewissern Sie sich, ob alles funktioniert, indem Sie den Dienststatus von Grafana überprüfen:

      • sudo systemctl status grafana-server

      Wie zuvor wird die Ausgabe melden, dass Grafana active (running) ist.

      Rufen Sie nun https://your_domain in Ihrem Webbrowser auf. Um zum Fenster zum Anmelden zurückzukehren, bewegen Sie den Cursor links unten im Bildschirm zu Ihrem Avatar und klicken Sie auf die Option Abmelden, die angezeigt wird.

      Vergewissern Sie sich nach dem Abmelden, dass es keine Schaltfläche zum Anmelden gibt und Sie sich nicht anmelden können, ohne Anmeldedaten einzugeben.

      Nun ist Grafana vollständig konfiguriert und einsatzbereit. Als Nächstes können Sie den Anmeldeprozess für Ihre Organisation vereinfachen, indem Sie über GitHub authentifizieren.

      (Optional) Schritt 5 — Einrichten einer GitHub OAuth-Anwendung

      Für einen alternativen Ansatz zur Anmeldung können Sie Grafana für eine Authentifizierung über GitHub konfigurieren, womit allen Mitgliedern autorisierter GitHub-Organisationen Zugriff gewährt wird. Dies kann besonders nützlich sein, wenn Sie möchten, dass verschiedene Entwickler zusammenarbeiten und Metriken aufrufen können, ohne spezielle Anmeldedaten für Grafana erstellen zu müssen.

      Melden Sie sich zunächst bei einem GitHub-Konto, das mit Ihrer Organisation verknüpft ist, an und navigieren Sie dann zu Ihrer GitHub-Profilseite unter https://github.com/settings/profile.

      Wechseln Sie den Einstellungskontext, indem Sie auf der linken Seite des Bildschirms auf Ihren Namen klicken und dann im Dropdown-Menü Ihre Organisation auswählen. Dadurch wird der Kontext von Persönliche Einstellungen in Organisationseinstellungen geändert.

      Im nächsten Bildschirm sehen Sie Ihr Organisationsprofil, in dem Sie Einstellungen wie den Anzeigenamen der Organisation, die E-Mail-Adresse der Organisation und die URL der Organisation ändern können.

      Da Grafana OAuth, einen offenen Standard zum Gewähren von Zugriff auf lokale Ressourcen an andere Remotebenutzer und Authentifizieren von Benutzern über GitHub nutzt, müssen Sie innerhalb von GitHub eine neue OAuth-Anwendung erstellen.

      Klicken Sie auf den Link OAuth-Anwendungen unter Entwicklereinstellungen unten links im Bildschirm.

      Wenn Sie in GitHub nicht bereits über OAuth-Anwendungen verfügen, die mit Ihrer Organisation verknüpft sind, erhalten Sie den Hinweis, dass keine Anwendungen im Besitz der Organisation sind. Andernfalls sehen Sie eine Liste der OAuth-Anwendungen, die bereits mit Ihrem Konto verknüpft sind.

      Klicken Sie auf die Schaltfläche Neue OAuth-Anwendung, um fortzufahren.

      Geben Sie im nächsten Bildschirm folgende Details zu Ihrer Grafana-Installation ein:

      • Anwendungsname: Damit können Sie Ihre verschiedenen OAuth-Anwendungen voneinander unterscheiden.
      • URL der Homepage: Dadurch erfährt GitHub, wo sich Grafana befindet. Geben Sie in dieses Feld https://your_domain ein, wobei Sie your_domain durch Ihre Domäne ersetzen.
      • Anwendungsbeschreibung: Damit wird eine Beschreibung des Zwecks Ihrer OAuth-Anwendung angegeben.
      • Callback-URL für Anwendung: Das ist die Adresse, an die Benutzer nach der erfolgreichen Authentifizierung weitergeleitet werden. Für Grafana muss dieses Feld https://your_domain/login/github lauten.

      Denken Sie daran, dass Grafana-Benutzer, die sich über GitHub anmelden, die Werte sehen, die Sie in den ersten drei vorangehenden Feldern eingegeben haben; geben Sie also sinnvolle und passende Werte ein.

      Am Ende wird das Formular in etwa so aussehen:

      GitHub Register OAuth-Anwendung

      Klicken Sie auf die grüne Schaltfläche Anwendung registrieren.

      Sie werden nun auf eine Seite weitergeleitet, die die Client-ID und das Clientgeheimnis enthält, die mit Ihrer neuen OAuth-Anwendung verknüpft sind. Notieren Sie sich beide Werte, da Sie sie der Hauptkonfigurationsdatei von Grafana hinzufügen müssen, um die Einrichtung abzuschließen.

      Achtung: Bewahren Sie Ihre Client-ID und das Clientgeheimnis an einem sicheren, nicht öffentlichen Ort auf, da diese Daten als Grundlage für Angriffe dienen können.

      Nach der Erstellung Ihrer GitHub OAuth-Anwendung können Sie Grafana nun neu konfigurieren, sodass GitHub zur Authentifizierung genutzt wird.

      (Optional) Schritt 6 — Konfigurieren von Grafana als GitHub OAuth-Anwendung

      Um die GitHub-Authentifizierung für Ihr Grafana-Setup zu abzuschließen, werden Sie nun einige Änderungen an Ihren Grafana-Konfigurationsdateien vornehmen.

      Öffnen Sie zunächst die Grafana-Hauptkonfigurationsdatei.

      • sudo nano /etc/grafana/grafana.ini

      Suchen Sie die Überschrift [auth.github] und heben Sie die Kommentierung dieses Abschnitts auf, indem Sie das ;-Zeichen am Anfang der einzelnen Zeilen entfernen (außer bei ;allowed_domains = und ;team_ids=, die in diesem Tutorial nicht geändert werden).

      Nehmen Sie als Nächstes folgende Änderungen vor:

      • Setzen Sie enabled und allow_sign_up auf true. Dadurch wird die GitHub-Authentifizierung aktiviert und Mitglieder der zugelassenen Organisation können Konten selbst erstellen. Beachten Sie, dass sich diese Einstellung von der Eigenschaft allow_sign_up unter [users] unterscheidet, die Sie in Schritt 4 geändert haben.
      • Setzen Sie client_id und client_secret auf die Werte, die Sie beim Erstellen Ihrer GitHub OAuth-Anwendung erhalten haben.
      • Verwenden Sie für allowed_organizations den Namen Ihrer Organisation, damit sich nur Mitglieder Ihrer Organisation bei Grafana registrieren und anmelden können.

      Die vollständige Konfiguration wird wie folgt aussehen:

      /etc/grafana/grafana.ini

      ...
      [auth.github]
      enabled = true
      allow_sign_up = true
      client_id = your_client_id_from_github
      client_secret = your_client_secret_from_github
      scopes = user:email,read:org
      auth_url = https://github.com/login/oauth/authorize
      token_url = https://github.com/login/oauth/access_token
      api_url = https://api.github.com/user
      ;allowed_domains =
      ;team_ids =
      allowed_organizations = your_organization_name
      ...
      

      Sie haben Grafana nun alles gesagt, was die Anwendung über GitHub wissen muss. Zum Abschließen der Einrichtung müssen Sie Umleitungen hinter einem Reverseproxy aktivieren. Dazu wird ein Wert root_url unter der Überschrift [server] festgelegt.

      /etc/grafana/grafana.ini

      ...
      [server]
      root_url = https://your_domain
      ...
      

      Speichern Sie Ihre Konfiguration und schließen Sie die Datei.

      Starten Sie Grafana anschließend neu, um die Änderungen zu aktivieren:

      • sudo systemctl restart grafana-server

      Vergewissern Sie sich abschließend, dass der Dienst ausgeführt wird.

      • sudo systemctl status grafana-server

      Die Ausgabe wird anzeigen, dass der Dienst active (running) ist.

      Testen Sie Ihr neues Authentifizierungssystem nun durch Navigieren zu https://your_domain. Wenn Sie bereits bei Grafana angemeldet sind, fahren Sie mit der Maus über das Avatar-Logo in der linken unteren Ecke des Bildschirms und klicken Sie im zweiten Menü, das neben Ihrem Namen erscheint, auf Abmelden.

      Auf der Anmeldeseite sehen Sie unter der ursprünglichen Schaltfläche zum Anmelden einen neuen Bereich, der eine Schaltfläche zum Anmelden mit GitHub inklusive des GitHub-Logos enthält.

      Grafana-Anmeldeseite mit GitHub

      Klicken Sie auf die Schaltfläche Anmelden mit GitHub, um an GitHub weitergeleitet zu werden, wo Sie sich bei Ihrem GitHub-Konto anmelden und Ihre Absicht zum Autorisieren von Grafana bestätigen können.

      Klicken Sie auf die grüne Schaltfläche your_github_organization autorisieren.

      Anmerkung: Stellen Sie sicher, dass Ihr GitHub-Konto Mitglied Ihrer zugelassenen Organisation ist und Ihre Grafana-E-Mail-Adresse mit Ihrer GitHub-E-Mail-Adresse übereinstimmt. Wenn Sie versuchen, sich bei einem GitHub-Konto zu authentifizieren, das kein Mitglied Ihrer zugelassenen Organisation ist, erhalten Sie eine Meldung zu Anmeldung fehlgeschlagen, in der Ihnen Folgendes mitgeteilt wird: Benutzer kein Mitglied einer der erforderlichen Organisationen.

      Sie werden nun mit Ihrem vorhandenen Grafana-Konto angemeldet. Wenn für den Benutzer, als der Sie sich angemeldet haben, noch kein Grafana-Konto vorhanden ist, wird Grafana ein neues Benutzerkonto mit Viewer-Berechtigungen erstellen, damit neue Anwender ausschließlich vorhandene Dashboards verwenden können.

      Um die Standardberechtigungen für neue Benutzer zu ändern, öffnen Sie die Hauptkonfigurationsdatei von Grafana zur Bearbeitung.

      • sudo nano /etc/grafana/grafana.ini

      Suchen Sie die Direktive auto_assign_org_role unter der Überschrift [users] und heben Sie die Kommentierung der Einstellung auf, indem Sie das ;-Zeichen am Anfang der Zeile entfernen.

      Setzen Sie die Direktive auf einen der folgenden Werte:

      • Viewer — kann nur vorhandene Dashboards verwenden
      • Editor — kann Dashboards verwenden, ändern und hinzufügen
      • Admin — kann alles tun

      In diesem Tutorial wird die automatische Zuordnung auf Viewer gesetzt:

      /etc/grafana/grafana.ini

      ...
      [users]
      ...
      auto_assign_org_role = Viewer
      ...
      

      Sobald Sie Ihre Änderungen gespeichert haben, schließen Sie die Datei und starten Sie Grafana neu:

      • sudo systemctl restart grafana-server

      Überprüfen Sie den Status des Diensts:

      • sudo systemctl status grafana-server

      Wie zuvor wird der Status active (running) lauten.

      Nun haben Sie Grafana so konfiguriert, dass Mitglieder Ihrer GitHub-Organisation Ihre Grafana-Installation registrieren und verwenden können.

      Zusammenfassung

      In diesem Tutorial haben Sie Grafana installiert, konfiguriert und gesichert und außerdem erfahren, wie sich Mitglieder Ihrer Organisation über GitHub authentifizieren können.

      Um Ihre aktuelle Grafana-Installation zu erweitern, konsultieren Sie die Liste der offiziellen und von der Community entwickelten Dashboards und Plugins. Um mehr über die allgemeine Verwendung von Grafana zu erfahren, konsultieren Sie die offizielle Grafana-Dokumentation oder unsere anderen Überwachungsleitfäden.



      Source link

      Cómo instalar y proteger Grafana en Ubuntu 20.04


      El autor seleccionó el COVID-19 Relief Fund para que reciba una donación como parte del programa Write for DOnations.

      Introducción

      Grafana es una herramienta de visualización y monitoreo de datos de código abierto que se integra con datos complejos de fuentes como Prometheus, InfluxDB, Graphite y ElasticSearch. Grafana le permite crear alertas, notificaciones y filtros ad-hoc para sus datos, a la vez que facilita la colaboración con los compañeros de equipo mediante características de uso compartido integradas.

      En este tutorial, instalará Grafana y la protegerá con un certificado SSL y un proxy inverso de Nginx. Una vez que haya configurado Grafana, tendrá la opción de configurar la autenticación del usuario a través de GitHub, lo que le permitirá organizar mejor los permisos de su equipo.

      Requisitos previos

      Para seguir este tutorial, necesitará lo siguiente:

      Paso 1: Instalar Grafana

      En este primer paso, instalará Grafana en su servidor de Ubuntu 20.04. Puede instalar Grafana descargándola directamente desde su sitio web oficial, o bien mediante un repositorio de APT. Debido a que un repositorio de APT facilita la instalación y administración de las actualizaciones de Grafana, en este tutorial utilizará ese método.

      Descargue la clave GPG de Grafana con wget y, luego, canalice el resultado a apt-key. Esto agregará la clave a la lista de claves de confianza de la instalación de APT, que le permitirá descargar y verificar el paquete Grafana firmado con GPG:

      • wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -

      En este comando, la opción -q desactiva el mensaje de actualización de estado para wget y -O arroja como resultado el archivo que descargó a la terminal. Estas dos opciones aseguran que solo el contenido del archivo descargado se canalice a apt-key.

      A continuación, agregue el repositorio de Grafana a las fuentes de APT:

      • sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main"

      Actualice el caché de APT para actualizar las listas de paquetes:

      Ahora, puede proceder con la instalación:

      Una vez que se haya instalado Grafana, utilice systemctl para iniciar el servidor de Grafana:

      • sudo systemctl start grafana-server

      A continuación, verifique el estado del servidor para comprobar que Grafana se esté ejecutando:

      • sudo systemctl status grafana-server

      Recibirá un resultado similar a este:

      Output

      ● grafana-server.service - Grafana instance Loaded: loaded (/lib/systemd/system/grafana-server.service; disabled; vendor preset: enabled) Active: active (running) since Thu 2020-05-21 08:08:10 UTC; 4s ago Docs: http://docs.grafana.org Main PID: 15982 (grafana-server) Tasks: 7 (limit: 1137) ...

      Este resultado contiene información sobre el proceso de Grafana, incluido el estado, el identificador de procesos principal (PID) y más. active (running) indica que el proceso se está ejecutando correctamente.

      Por último, habilite el servicio para que inicie Grafana de forma automática en el arranque:

      • sudo systemctl enable grafana-server

      Recibirá el siguiente resultado:

      Output

      Synchronizing state of grafana-server.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable grafana-server Created symlink /etc/systemd/system/multi-user.target.wants/grafana-server.service → /usr/lib/systemd/system/grafana-server.service.

      Esto confirma que systemd ha creado los enlaces simbólicos necesarios para iniciar Grafana de manera automática.

      Grafana ya está instalada y lista para su uso. A continuación, protegerá la conexión a Grafana con un proxy inverso y un certificado SSL.

      Paso 2: Configurar el proxy inverso

      El uso de un certificado SSL garantizará la seguridad de los datos al cifrar la conexión desde y hacia Grafana. Sin embargo, para utilizar esta conexión, primero deberá volver a configurar Nginx para que actúe como un proxy inverso para Grafana.

      Abra el archivo de configuración de Nginx que creó al configurar el bloque de servidor de Nginx con Let’s Encrypt en los Requisitos previos. Puede utilizar cualquier editor de texto, pero en este tutorial lo haremos con nano:

      • sudo nano /etc/nginx/sites-available/your_domain

      Busque el siguiente bloque:

      /etc/nginx/sites-available/your_domain

      ...
          location / {
              try_files $uri $uri/ =404;
          }
      ...
      

      Debido a que ya configuró Nginx para que se comunique a través de SSL y a que todo el tráfico web hacia su servidor ya pasa a través de Nginx, solo debe indicar a Nginx que reenvíe todas las solicitudes a Grafana, que de forma predeterminada se ejecuta en el puerto 3000.

      Elimine la línea try_files existente en este location block (bloque de ubicación) y sustitúyala por la siguiente opción proxy_pass:

      /etc/nginx/sites-available/your_domain

      ...
          location / {
              proxy_pass http://localhost:3000;
          }
      ...
      

      Esto permitirá asignar el proxy al puerto apropiado. Una vez que haya terminado, pulse CTRL+X, Y y, luego, ENTER si utiliza nano, para guardar y cerrar el archivo.

      Ahora, pruebe los nuevos ajustes para asegurarse de que todo se configuró correctamente:

      Recibirá el siguiente resultado:

      Output

      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      Por último, vuelva a cargar Nginx para habilitar los cambios:

      • sudo systemctl reload nginx

      Ahora puede acceder a la pantalla de inicio de sesión predeterminada de Grafana orientando el navegador web a https://your_domain. Si no puede llegar a Grafana, verifique que el firewall esté configurado para permitir el tráfico en el puerto 443 y, luego, vuelva a realizar lo indicado anteriormente.

      Ahora que la conexión a Grafana está cifrada, puede implementar medidas de seguridad adicionales, y lo primero será modificar las credenciales administrativas predeterminadas de Grafana.

      Paso 3: Actualizar las credenciales

      Debido a que cada instalación de Grafana utiliza las mismas credenciales administrativas de forma predeterminada, una práctica recomendada es modificar la información de inicio de sesión lo antes posible. En este paso, actualizará las credenciales para mejorar la seguridad.

      Diríjase primero a https://your_domain desde el navegador Con esto, se mostrará la pantalla de inicio de sesión predeterminada en la que verá el logotipo de Grafana, un formulario que le solicitará ingresar un correo electrónico o nombre de usuario y una contraseña, el botón Log in (Iniciar sesión) y el vínculo ¿Olvidó la contraseña?

      Inicio de sesión de Grafana

      Escriba admin en el campo del correo electrónico o nombre de usuario y de la contraseña y, luego, haga clic en el botón Log in.

      En la siguiente pantalla, se le solicitará cambiar la contraseña predeterminada para que la cuenta sea más segura:

      Cambiar contraseña

      Escriba la contraseña que quiere utilizar en los campos Nueva contraseña y Confirmar contraseña nueva.

      Desde aquí, puede hacer clic en Enviar para guardar la nueva información o pulsar Omitir para saltar este paso. Si omite este paso, se le solicitará cambiar la contraseña la próxima vez que inicie sesión.

      Para aumentar la seguridad de la configuración de Grafana, haga clic en Enviar. Será redirigido al panel Bienvenido a Grafana:

      Panel de la página principal

      Ya ha protegido la cuenta modificando las credenciales predeterminadas. A continuación, realizará cambios en la configuración de Grafana para que nadie pueda crear una nueva cuenta de Grafana sin su permiso.

      Paso 4: Deshabilitar los registros y el acceso anónimo a Grafana

      Grafana proporciona opciones que permiten a los visitantes crear cuentas de usuario para sí mismos y obtener una vista previa de los paneles sin registrarse. Es posible que quiera permitir estas características cuando no se puede acceder a Grafana a través de Internet o cuando trabaja con datos de uso público, como los estados de servicio. Sin embargo, cuando utiliza Grafana en línea para trabajar con datos confidenciales, el acceso anónimo podría constituir un problema de seguridad. Para solucionar este problema, realice algunos cambios en la configuración de Grafana.

      Primero, abra el archivo de configuración principal de Grafana para editarlo:

      • sudo nano /etc/grafana/grafana.ini

      Busque la siguiente directiva allow_sign_up bajo el encabezado [users]:

      /etc/grafana/grafana.ini

      ...
      [users]
      # disable user signup / registration
      ;allow_sign_up = true
      ...
      

      Al habilitar esta directiva con true, se agrega un botón Sign up (Registrarse) a la pantalla de inicio de sesión, que permite a los usuarios registrarse y acceder a Grafana.

      Al deshabilitar esta directiva con false, se quita el botón Sign Up y se refuerza la seguridad y la privacidad de Grafana.

      Borre el signo ; del comienzo de la línea y, luego, establezca la opción como false para eliminar el comentario de esta directiva:

      /etc/grafana/grafana.ini

      ...
      [users]
      # disable user signup / registration
      allow_sign_up = false
      ...
      

      A continuación, busque la siguiente directiva enabled bajo el encabezado [auth.anonymous]:

      /etc/grafana/grafana.ini

      ...
      [auth.anonymous]
      # enable anonymous access
      ;enabled = false
      ...
      

      Al establecer enabled como true, se permite el acceso de usuarios no registrados a los paneles de datos; al establecer esta opción como false, se permite el acceso solo a los usuarios registrados.

      Borre el signo ; del comienzo de la línea y, luego, establezca la opción como false para eliminar el comentario de esta directiva.

      /etc/grafana/grafana.ini

      ...
      [auth.anonymous]
      # enable anonymous access
      enabled = false
      ...
      

      Guarde el archivo y salga del editor de texto.

      Para habilitar los cambios, reinicie Grafana:

      • sudo systemctl restart grafana-server

      Compruebe el estado del servicio de Grafana para verificar que todo funciona correctamente:

      • sudo systemctl status grafana-server

      Al igual que antes, el resultado mostrará active (running), lo que indica que Grafana se está ejecutando.

      Ahora, dirija el navegador hacia https://your_domain. Para volver a la pantalla de registro ubique el cursor en su avatar, que se encuentra en la parte inferior izquierda de la pantalla, y haga clic en la opción Cerrar sesión que aparecerá.

      Una vez que haya cerrado sesión, verifique que no haya ningún botón Sign Up y que no pueda iniciar sesión sin introducir las credenciales de inicio de sesión.

      En este momento, Grafana está totalmente configurada y lista para su uso. A continuación, puede simplificar el proceso de inicio de sesión para su organización al autenticar a través de GitHub.

      Paso 5 (opcional): Configurar una aplicación OAuth de GitHub

      Un enfoque alternativo para iniciar sesión consiste en configurar Grafana para que se autentique a través de GitHub, que proporciona acceso de inicio de sesión a todos los miembros de las organizaciones autorizadas de GitHub. Esto puede resultar particularmente útil cuando quiere permitir que varios desarrolladores colaboren y accedan a las métricas sin tener que crear credenciales específicas para Grafana.

      Primero, inicie sesión en una cuenta de GitHub asociada con su organización y, luego, vaya a su página de perfil de GitHub en https://github.com/settings/profile.

      Haga clic en su nombre, que está en el margen izquierdo de la pantalla y, luego, seleccione su organización en el menú desplegable para cambiar el contexto de configuración Esto permitirá cambiar el contexto de configuración personal a configuración de la organización.

      En la siguiente pantalla, verá el perfil de la organización, donde podrá cambiar los ajustes, como el nombre para mostrar de la organización, el correo electrónico y la dirección URL de la organización.

      Debido a que Grafana utiliza OAuth (un estándar abierto para conceder acceso a terceros remotos a los recursos locales) para autenticar a los usuarios a través de GitHub, deberá crear una nueva aplicación OAuth en GitHub.

      Haga clic en el enlace Aplicaciones OAuth en Opciones de configuración para desarrolladores ubicado en el margen inferior izquierdo de la pantalla.

      Si aún no tiene ninguna aplicación OAuth asociada con su organización en GitHub, se le indicará que no hay aplicaciones que pertenezcan a la organización. De lo contrario, verá una lista de las aplicaciones OAuth que ya están conectadas a su cuenta.

      Haga clic en el botón Nueva aplicación OAuth para continuar.

      En la siguiente pantalla, complete los siguientes detalles sobre la instalación de Grafana:

      • Nombre de la aplicación: le ayuda a distinguir las diferentes aplicaciones OAuth que posea.
      • URL de la página principal: le indica a GitHub dónde encontrar a Grafana. Escriba https://your_domain en este campo, sustituyendo your_domain por su dominio.
      • Descripción de la aplicación: proporciona una descripción del propósito de su aplicación OAuth.
      • URL de devolución de llamada de la aplicación: es la dirección a la que se enviará a los usuarios una vez que se autentiquen correctamente. En el caso de Grafana, este campo debe establecerse como https://your_domain/login/github.

      Tenga en cuenta que los usuarios de Grafana que inicien sesión a través de GitHub verán los valores que ingresó en los tres primeros campos, así que asegúrese de agregar información importante y apropiada.

      Una vez completado, el formulario tendrá un aspecto similar al siguiente:

      Registro de aplicación OAuth de GitHub

      Haga clic en el botón verde Registrar la aplicación.

      Ahora será redireccionado a una página que contiene el Identificador de cliente y Clave secreta de cliente asociados con la nueva aplicación OAuth. Tenga en cuenta ambos valores, porque deberá agregarlos al archivo de configuración principal de Grafana para completar la configuración.

      Advertencia: Asegúrese de mantener su Identificador de cliente y Clave secreta de cliente en una ubicación segura y privada, porque podrían utilizarse para un ataque.

      Ahora que creó la aplicación OAuth de GitHub, está listo para volver a configurar Grafana de modo que le permita utilizar GitHub para la autenticación.

      Paso 6 (opcional): Configurar Grafana como una aplicación OAuth de GitHub

      Ahora realizará algunas modificaciones en los archivos de configuración de Grafana para completar la autenticación de GitHub para utilizarlo en la configuración de Grafana.

      Para comenzar, abra el archivo de configuración principal de Grafana.

      • sudo nano /etc/grafana/grafana.ini

      Busque el encabezado [auth.github] y borre el signo ; del comienzo de cada línea, a excepción de ;allowed_domains = y ;team_ids = (que no cambiaremos en este tutorial) para eliminar el comentario de esta sección.

      A continuación, realice los siguientes cambios:

      • Establezca enabled y allow_sign_up como true. Esto habilitará la autenticación de GitHub y permitirá que los miembros de la organización permitida puedan crear cuentas. Tenga en cuenta que esta opción de configuración es diferente a la propiedad allow_sign_up en [users] que modificó en el paso 4.
      • En client_id y client_secret ingrese los valores que obtuvo al crear la aplicación OAuth de GitHub.
      • En allowed_organizations ingrese el nombre de su organización para asegurarse de que solo los miembros de la empresa puedan registrarse e iniciar sesión en Grafana.

      La configuración completa tendrá el siguiente aspecto:

      /etc/grafana/grafana.ini

      ...
      [auth.github]
      enabled = true
      allow_sign_up = true
      client_id = your_client_id_from_github
      client_secret = your_client_secret_from_github
      scopes = user:email,read:org
      auth_url = https://github.com/login/oauth/authorize
      token_url = https://github.com/login/oauth/access_token
      api_url = https://api.github.com/user
      ;allowed_domains =
      ;team_ids =
      allowed_organizations = your_organization_name
      ...
      

      Ya le indicó a Grafana todo lo que necesita saber sobre GitHub. Para completar la configuración, deberá habilitar los redireccionamientos detrás de un proxy inverso. Para ello, se configura un valor root_url bajo el encabezado [server].

      /etc/grafana/grafana.ini

      ...
      [server]
      root_url = https://your_domain
      ...
      

      Guarde la configuración y cierre el archivo.

      A continuación, reinicie Grafana para habilitar los cambios:

      • sudo systemctl restart grafana-server

      Por último, verifique que el servicio esté activo y en ejecución.

      • sudo systemctl status grafana-server

      El resultado mostrará active (running), lo que indica que el servicio se está ejecutando.

      Ahora, diríjase a https://your_domain para probar el nuevo sistema de autenticación. Si ya inició sesión en Grafana, mantenga el mouse sobre el registro del avatar, ubicado en la esquina inferior izquierda de la pantalla, y haga clic en Cerrar sesión en el menú secundario que aparece junto a su nombre.

      En la página de inicio de sesión, verá una nueva sección debajo del botón Iniciar sesión original, que contiene el botón Iniciar sesión con GitHub con el logo de GitHub.

      Página de inicio de sesión con GitHub de Grafana

      Haga clic en el botón Iniciar sesión con GitHub para que el sistema lo redireccione a GitHub, en donde iniciará sesión en su cuenta de GitHub y confirmará que quiere autorizar a Grafana.

      Haga clic en el botón verde Autorizar your_github_organization.

      Nota: Asegúrese de que su cuenta de GitHub sea miembro de la organización aprobada y que la dirección de correo electrónico de Grafana coincida con la de GitHub. Si intenta autenticarse con una cuenta de GitHub que no pertenezca a la organización aprobada, recibirá el mensaje Error al iniciar sesión, en el que se le indica que el usuario no es miembro de una de las organizaciones requeridas.

      Ahora, habrá iniciado sesión con la cuenta de Grafana existente. Si aún no existe una cuenta de Grafana para el usuario con el que inició sesión, Grafana creará una nueva cuenta de usuario con permisos de visualización, lo que garantiza que los nuevos usuarios solo puedan utilizar los paneles existentes.

      Para modificar los permisos predeterminados para los nuevos usuarios, abra el archivo de configuración principal de Grafana para editarlo.

      • sudo nano /etc/grafana/grafana.ini

      Busque la directiva auto_assign_org_role bajo el encabezado [users] y borre el signo ; del principio de la línea para eliminar el comentario de la configuración.

      Establezca uno de los siguientes valores en la directiva:

      • Viewer (visualización): solo puede utilizar los paneles existentes
      • Editor: puede utilizar, modificar y agregar paneles
      • Admin: tiene permiso para realizar todas las acciones

      En este tutorial se establecerá auto-assign como Viewer:

      /etc/grafana/grafana.ini

      ...
      [users]
      ...
      auto_assign_org_role = Viewer
      ...
      

      Una vez que haya guardado los cambios, cierre el archivo y reinicie Grafana:

      • sudo systemctl restart grafana-server

      Compruebe el estado del servicio:

      • sudo systemctl status grafana-server

      Al igual que antes, el estado mostrará active (running).

      En este momento, ha configurado completamente Grafana para permitir que los miembros de su organización de GitHub puedan registrarse y utilizar la instalación de Grafana.

      Conclusión

      En este tutorial, instaló, configuró y protegió Grafana, y también aprendió cómo permitir que los miembros de su organización se autentiquen a través de GitHub.

      Para ampliar la instalación actual de Grafana, consulte la lista de paneles y complementos oficiales y creados por la comunidad. Para obtener más información sobre el uso de Grafana en general, consulte la documentación oficial de Grafana o alguno de nuestros tutoriales de monitoreo.



      Source link