Você pode usar o arquivo mongodb-prometheus-sample.yaml para distribuir um recurso MongoDB no seu cluster Kubernetes, com um ServiceMonitor para orientar o Prometheus na coleta de métricas
A amostra especifica um recurso MongoDB simples com um usuário, e o atributo spec.prometheus com autenticação HTTP básica e nenhum TLS. A amostra permite testar as métricas que o MongoDB envia para Prometheus.
Observação
Você não pode usar o Prometheus com um sistema de vários clusters Kubernetes.
Início rápido
Testamos esta configuração com a versão 0.54 do operador Prometheus.
Pré-requisitos
Kubernetes 1.16+
Elmo 3+
Instalar o operador Prometheus
Você pode instalar o operador Prometheus usando o Helm. Para saber mais, consulte as instruções de instalação.
Para instalar o operador Prometheus usando o Helm, execute os seguintes comandos:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm install prometheus prometheus-community/kube-prometheus-stack \ --namespace <prometheus-system> \ --create-namespace
Instale os Controladores MongoDB para o Operador Kubernetes
Execute o seguinte comando para instalar o Operador Kubernetes e criar um namespace para conter o Operador Kubernetes e recursos:
helm install mongodb-kubernetes-operator mongodb/mongodb-kubernetes \ --namespace <mongodb> --create-namespace
Para saber mais, consulte Instalar os Controladores MongoDB para Kubernetes Operator.
Crie um recurso MongoDB
Você pode usar o arquivo mongodb-prometheus-sample.yaml para distribuir um recurso MongoDB no seu cluster Kubernetes, com um ServiceMonitor para orientar o Prometheus na coleta de métricas
Você pode aplicar a amostra diretamente com o seguinte comando:
Observação
Specify the full path to the mongodb-prometheus-sample.yaml file. Ensure you specify spec.credentials and spec.cloudManager.configMapRef.name.
kubectl apply -f <mongodb-prometheus-sample.yaml>
This command creates two secrets that contain authentication for a new MongoDB user and basic HTTP authentication for the Prometheus endpoint. The command creates both secrets in the mongodb namespace.
This command also creates a ServiceMonitor that configures Prometheus to consume this resource's metrics. This command creates the ServiceMonitor in the prometheus-system namespace.
Opcional: habilite o TLS no endpoint do Prometheus
Instale o Gerenciador de certificados
Para instalar o cert-manager usando o Helm, consulte a documentação de instalação doert-manager.
Para criar um
Issuerde gerenciamento seguro, consulte a documentação de configuração de gerenciamento certoTo create a certificate, see the cert-manager usage documentation.
Habilitar TLS no CRD do MongoDB
Importante
NÃO use esta configuração em ambientes de Produção! Um especialista em segurança deve orientá-lo sobre como configurar o TLS.
To enable TLS, you must add a new entry to the spec.prometheus section of the MongoDB custom resource. Run the following patch operation to add the needed entry.
Observação
tlsSecretKeyRef.name points at a secret of type kubernetes.io/tls that holds a Server certificate.
kubectl patch mdbc mongodb --type='json' \ -p='[{"op": "add", "path": "/spec/prometheus/tlsSecretKeyRef", "value":{"name": "prometheus-target-cert"}}]' \ --namespace mongodb
A seguinte resposta é exibida:
mongodbenterprise.mongodbenterprise.mongodb.com/mongodb patched
Após alguns minutos, o recurso MongoDB deve retornar à fase de Execução. Agora você deve configurar o ServiceMonitor do Prometheus para apontar para o ponto de extremidade HTTPS.
Atualizar o ServiceMonitor
Para atualizar o ServiceMonitor, execute o seguinte comando para corrigir o recurso novamente:
kubectl patch servicemonitors mongodb-sm --type='json' \ -p=' [ {"op": "replace", "path": "/spec/endpoints/0/scheme", "value": "https"}, {"op": "add", "path": "/spec/endpoints/0/tlsConfig", "value": {"insecureSkipVerify": true}} ] ' \ --namespace mongodb
A seguinte resposta é exibida:
servicemonitor.monitoring.coreos.com/mongodb-sm patched
With these changes, the new ServiceMonitor points to the HTTPS endpoint (defined in /spec/endpoints/0/scheme). You also set spec/endpoints/0/tlsConfig/insecureSkipVerify to true, so that Prometheus doesn't verify the TLS certificates on MongoDB's end.
O Prometheus agora deve ser capaz de raspar o alvo MongoDB usando HTTPS.
mongodb-prometheus-sample.yaml
Crie o seguinte arquivo mongodb-prometheus-sample.yaml para implantar um recurso do MongoDB em seu cluster do Kubernetes, com um ServiceMonitor para indicar ao Prometheus como consumir dados de métricas dele.
Este arquivo de amostra especifica um recurso MongoDB simples com um usuário, e o atributo spec.prometheus com autenticação HTTP básica e nenhum TLS. A amostra permite testar as métricas que o MongoDB envia para Prometheus.
Para saber mais, consulte Configurações do Prometheus.
--- apiVersion: mongodb.com/v1 kind: MongoDB metadata: name: my-replica-set spec: members: 3 version: 8.0.0 cloudManager: configMapRef: name: <project-configmap> credentials: <credentials-secret> type: ReplicaSet persistent: true prometheus: passwordSecretRef: # SecretRef to a Secret with a 'password' entry on it. name: metrics-endpoint-password # change this value to your Prometheus username username: prometheus-username # Enables HTTPS on the prometheus scrapping endpoint # This should be a reference to a Secret type kuberentes.io/tls # tlsSecretKeyRef: # name: <prometheus-tls-cert-secret> # Port for Prometheus, default is 9216 # port: 9216 # # Metrics path for Prometheus, default is /metrics # metricsPath: '/metrics' --- apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: This needs to match `spec.ServiceMonitorSelector.matchLabels` from your `prometheuses.monitoring.coreos.com` resouce. labels: release: prometheus name: mongodb-sm Make sure this namespace is the same as in `spec.namespaceSelector`. namespace: mongodb spec: endpoints: Configuring a Prometheus Endpoint with basic Auth. `prom-secret` is a Secret containing a `username` and `password` entries. - basicAuth: password: key: password name: metrics-endpoint-creds username: key: username name: metrics-endpoint-creds # This port matches what we created in our MongoDB Service. port: prometheus # If using HTTPS enabled endpoint, change scheme to https scheme: http # Configure different TLS related settings. For more information, see: # https://github.com/prometheus-operator/prometheus-operator/blob/main/pkg/apis/monitoring/v1/types.go#L909 # tlsConfig: # insecureSkipVerify: true What namespace to watch namespaceSelector: matchNames: # Change this to the namespace the MongoDB resource was deployed. - mongodb Service labels to match selector: matchLabels: app: my-replica-set-svc --- apiVersion: v1 kind: Secret metadata: name: metrics-endpoint-creds namespace: mongodb type: Opaque stringData: password: 'Not-So-Secure!' username: prometheus-username ...
Exemplos
Os exemplos a seguir mostram as definições de recursos necessárias para usar o Prometheus com seu recurso do MongoDB.
Recurso do MongoDB com Prometeus
Para saber mais, consulte Configurações do Prometheus.
--- apiVersion: mongodb.com/v1 kind: MongoDB metadata: name: my-replica-set spec: members: 3 version: 8.0.0 cloudManager: configMapRef: name: <project-configmap> credentials: <credentials-secret> type: ReplicaSet persistent: true prometheus: passwordSecretRef: name: metrics-endpoint-password username: prometheus-username ...
Monitor de serviço
--- apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: labels: release: prometheus name: mongodb-sm namespace: mongodb spec: endpoints: - basicAuth: password: key: password name: metrics-endpoint-creds username: key: username name: metrics-endpoint-creds port: prometheus scheme: http namespaceSelector: matchNames: - mongodb selector: matchLabels: app: my-replica-set-svc ...
Credenciais de endpoint
--- apiVersion: v1 kind: Secret metadata: name: metrics-endpoint-creds namespace: mongodb type: Opaque stringData: password: 'Not-So-Secure!' username: prometheus-username ...