Administra secretos en la configuración de métricas del Agente de operaciones
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Configurar algunas de las integraciones de terceros, requiere que
proporciones secretos, como contraseñas, para los receptores de métricas
del Agente de operaciones. De forma predeterminada, estos secretos se almacenan como texto simple en el archivo
config.yaml del agente. Estos secretos se incluyen en los registros del sistema
que escribe el agente y se transmiten a Cloud Logging, lo que los expone
más allá de la máquina virtual (VM) en la que se ejecuta
el Agente de operaciones.
A partir de la versión 2.57.0 del Agente de operaciones,
puedes usar un proveedor de OpenTelemetry integrado en Secret Manager para borrar
los secretos de texto simple de los archivos de configuración.
Un proveedor es un componente de configuración de OpenTelemetry,
análogo a los componentes de receptor y procesador. Cada proveedor tiene un
tipo, y cada tipo de proveedor asigna un identificador específico en la
configuración a un valor.
El proveedor de googlesecretmanager asigna identificadores de
Secret Manager a los secretos, como contraseñas, tokens y claves de API,
que almacenaste en Secret Manager. Usar
el proveedor googlesecretmanager ofrece los siguientes beneficios:
Mayor seguridad: Los archivos de configuración no contienen
información sensible, como contraseñas. Los secretos reales se almacenan
en Secret Manager, un servicio diseñado específicamente para
almacenar y administrar datos sensibles de forma segura, además de acceder a ellos.
Menor riesgo de exposición: Secret Manager recupera
secretos durante la inicialización del Agente de operaciones, lo que evita
que los secretos de texto simple se asienten por accidente en los registros.
Solo puedes usar googlesecretmanager en la configuración de la recopilación de
métricas en parámetros de configuración personalizados del Agente de operaciones. No uses el proveedor para
reemplazar secretos en la configuración de la recopilación de registros.
Antes de empezar
Para usar el proveedor de googlesecretmanager, debes habilitar la
API de Secret Manager y permitir el acceso a ella,
como se describe en los siguientes pasos:
After installing the Google Cloud CLI,
initialize it by running the following command:
Configura el proyecto predeterminado para Google Cloud CLI de la siguiente manera:
gcloud config set project PROJECT_ID
Antes de ejecutar el comando anterior, reemplaza la variable PROJECT_ID
por el identificador de tu proyecto de Google Cloud .
Enable the Secret Manager API:
gcloudservicesenablesecretmanager.googleapis.com
Actualiza los permisos de acceso de OAuth para que la instancia incluya
el permiso que requiere Secret Manager, https://www.googleapis.com/auth/cloud-platform:
Otorga al usuario que administra los parámetros de configuración del Agente de operaciones
los permisos necesarios para crear y administrar secretos. El rol de Identity and Access Management
roles/secretManager.secretAdmin incluye los permisos
necesarios:
Antes de ejecutar el comando anterior, reemplaza las siguientes variables:
PROJECT_ID: es el identificador de tu proyecto de
Google Cloud .
USER_EMAIL: es la dirección del usuario al que se le otorga
el rol.
Otorga a la cuenta de servicio asociada a la VM los permisos
necesarios para acceder a los secretos. El rol de Identity and Access Management
roles/secretManager.secretAccessor incluye los permisos
necesarios:
Antes de ejecutar el comando anterior, reemplaza las siguientes variables:
PROJECT_ID: es el identificador de tu proyecto de Google Cloud .
SERVICE_ACCT_EMAIL: es la dirección de la
cuenta de servicio asociada a la VM.
Reemplaza los secretos de texto simple por los administrados
Para dejar de usar secretos de texto simple en tus archivos de configuración
con Secret Manager y el proveedor de googlesecretmanager,
haz lo siguiente:
Crea un secreto en Secret Manager para cada secreto de texto simple
en tus archivos de configuración.
Reemplaza cada secreto de texto simple en tus archivos de configuración por una referencia
al secreto correspondiente en Secret Manager.
Por ejemplo, si usas un receptor de métricas mysql,
tu archivo de configuración podría incluir una entrada como la siguiente:
receivers:
mysql:
type: mysql
username: root
password: plaintext-secret
En este ejemplo, debes colocar la cadena plaintext-secret
en Secret Manager y, luego, reemplazar
el secreto de texto simple por una referencia al secreto administrado.
Crea secretos de Secret Manager para los secretos de texto simple
Para crear un secreto de Secret Manager que incluya el secreto de texto simple
plaintext-secret, ejecuta el siguiente comando:
Para obtener más información sobre cómo almacenar secretos, controlar sus versiones y acceder a ellos en
Secret Manager, consulta
Crea un secreto.
Reemplaza secretos de texto simple
Para actualizar tus archivos de configuración, reemplaza cada secreto de texto simple
por una referencia al proveedor de googlesecretmanager y al nombre del recurso
del secreto administrado, como se muestra en el siguiente ejemplo:
receivers:
mysql:
type: mysql
username: root
password: ${googlesecretmanager:projects/PROJECT_ID/secrets/SECRET_NAME/versions/VERSION}
Reinicia el Agente de operaciones
Linux
Para reiniciar el Agente, ejecuta el siguiente comando en la instancia:
sudo systemctl restart google-cloud-ops-agent
Para confirmar que el Agente se haya reiniciado, ejecuta el siguiente comando y
verifica que los componentes “Agente de métricas” y “Agente de Logging” se hayan iniciado:
sudo systemctl status "google-cloud-ops-agent*"
Windows
Conéctate a la instancia a través de RDP o una herramienta similar y accede a Windows.
Haz clic con el botón derecho en el ícono de PowerShell y selecciona
Ejecutar como administrador para abrir una terminal de PowerShell con privilegios de administrador.
Para reiniciar el Agente, ejecuta el siguiente comando de PowerShell:
Restart-Service google-cloud-ops-agent -Force
Para confirmar que el agente se haya reiniciado, ejecuta el siguiente comando y
verifica que los componentes “Agente de métricas” y “Agente de Logging” se hayan iniciado:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-05 (UTC)"],[],[],null,["# Manage secrets in Ops Agent metric configuration\n\nConfiguring some of the third-party integrations requires you to\nprovide secrets, such as passwords, for the Ops Agent metric\nreceivers. By default, these secrets are stored as plaintext in the agent's\n`config.yaml` file. These secrets are included in system logs\nwritten by the agent and transmitted to Cloud Logging, exposing\nthe secrets beyond the virtual machine (VM) where the Ops Agent is\nrunning.\n\nStarting with Ops Agent version 2.57.0,\nyou can use an OpenTelemetry provider integrated [Secret Manager](/secret-manager/docs/overview) to eliminate\nplaintext secrets in your configuration files.\n\nA *provider* is an OpenTelemetry configuration component,\nanalogous to the receiver and processor components. Each provider has a\ntype, and each type of provider maps a specific identifier in the\nconfiguration to a value.\n\nThe `googlesecretmanager` provider maps Secret Manager\nidentifiers to the secrets, like passwords, tokens, and API keys, that you've\nstored in Secret Manager. Using the\n`googlesecretmanager` provider offers the following benefits:\n\n- **Enhanced security** : Your configuration files don't contain sensitive information like passwords. The actual secrets are stored in [Secret Manager](/secret-manager/docs/overview), a service designed specifically for securely storing, accessing, and managing sensitive data.\n- **Reduced risk of exposure**: Secret Manager fetches secrets during initialization of the Ops Agent, which prevents plaintext secrets from accidentally being recorded in logs.\n\nYou can use the `googlesecretmanager` only in the configuration of\nmetric collection in custom Ops Agent configurations. Don't use the provider to\nreplace secrets in the configuration of log collection.\n\nBefore you begin\n----------------\n\nTo use the `googlesecretmanager` provider, you must enable the\nSecret Manager API and permit access to the API,\nas described in the following steps:\n\n1.\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n After installation,\n [initialize](/sdk/docs/initializing) the Google Cloud CLI by running the following command:\n\n ```bash\n gcloud init\n ```\n\n\n If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n2. Set the default project for Google Cloud CLI:\n\n ```\n gcloud config set project PROJECT_ID\n ```\n\n Before you run the previous command, replace the \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\n variable with the identifier of your Google Cloud project.\n3.\n\n\n Enable the Secret Manager API:\n\n\n ```bash\n gcloud services enable secretmanager.googleapis.com\n ```\n4. Update the OAuth access scopes for your instance to include the required scope for Secret Manager, `https://www.googleapis.com/auth/cloud-platform`: \n\n ```\n gcloud compute instances set-service-account \"INSTANCE_ID\" \\\n --service-account \"SERVICE_ACCT_EMAIL\" \\\n --scopes \"https://www.googleapis.com/auth/cloud-platform\"\n ```\n\n Before you run the previous command, replace the following variables:\n - \u003cvar translate=\"no\"\u003eINSTANCE_ID\u003c/var\u003e: the identifier of your VM.\n - \u003cvar translate=\"no\"\u003eSERVICE_ACCT_EMAIL\u003c/var\u003e: the address of the service account associated with the VM.\n\n For more information, see\n [Access the Secret Manager API](/stackdriver/docs/solutions/agents/ops-agent/third-party/secret-manager/docs/accessing-the-api).\n5. Grant the user who manages the Ops Agent configurations the permissions needed to create and manage secrets. The Identity and Access Management role `roles/secretManager.secretAdmin` includes the necessary permissions: \n\n ```\n gcloud projects add-iam-policy-binding PROJECT_ID \\\n --member=\"user:USER_EMAIL\" \\\n --role=roles/secretManager.secretAdmin\n ```\n\n Before you run the previous command, replace the following variables:\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: the identifier of your Google Cloud project.\n - \u003cvar translate=\"no\"\u003eUSER_EMAIL\u003c/var\u003e: the address of the user being granted the role.\n6. Grant the service account associated with the VM the permissions it needs to access the secrets. The Identity and Access Management role `roles/secretManager.secretAccessor` includes the necessary permissions: \n\n ```\n gcloud projects add-iam-policy-binding PROJECT_ID \\\n --member=\"serviceAccount:SERVICE_ACCT_EMAIL\" \\\n --role=roles/secretManager.secretAccessor\n ```\n\n Before you run the previous command, replace the following variables:\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: the identifier of your Google Cloud project.\n - \u003cvar translate=\"no\"\u003eSERVICE_ACCT_EMAIL\u003c/var\u003e: the address of the service account associated with the VM.\n\nReplace plaintext secrets with managed secrets\n----------------------------------------------\n\nTo eliminate the use of plaintext secrets in your configuration files by\nusing Secret Manager and the `googlesecretmanager`\nprovider, do the following:\n\n1. Create a secret in Secret Manager for each plaintext secret in your configuration files.\n2. Replace each plaintext secret in your configuration files with a reference to the corresponding secret in Secret Manager.\n\nFor example, if you are using a `mysql` metric receiver, then\nyour configuration file might include an entry like the following: \n\n```\nreceivers:\n mysql:\n type: mysql\n username: root\n password: plaintext-secret\n```\n\nIn this example, you want to place the \u003cvar translate=\"no\"\u003eplaintext-secret\u003c/var\u003e\nstring into Secret Manager and then replace\nthe plaintext secret with a reference to the managed secret.\n\n### Create Secret Manager secrets\nfor plaintext secrets\n\nTo create a Secret Manager secret containing the plaintext secret `plaintext-secret`, run the following command: \n\n```\necho -n \"plaintext-secret\" | gcloud secrets create SECRET_NAME \\\n --replication-policy=\"automatic\" \\\n --data-file=-\n```\n\nBefore you run the previous command, replace the following variables:\n\n- \u003cvar translate=\"no\"\u003eplaintext-secret\u003c/var\u003e: Replace with your plaintext secret.\n- \u003cvar translate=\"no\"\u003eSECRET_NAME\u003c/var\u003e: Replace with a meaningful name for your secret.\n\nThe fully qualified resource name of your new secret has the following\nformat, with a \u003cvar translate=\"no\"\u003eVERSION\u003c/var\u003e of `1`: \n\n```\nprojects/PROJECT_ID/secrets/SECRET_NAME/versions/VERSION\n```\n\nFor more information about storing, versioning, and accessing secrets in\nSecret Manager, see\n[Create a secret](/secret-manager/docs/creating-and-accessing-secrets).\n\n### Replace plaintext secrets\n\nTo update your configuration files, replace each plaintext secret\nwith a reference to the `googlesecretmanager` provider and the resource\nname of the managed secret, as shown in the following example: \n\n```\nreceivers:\n mysql:\n type: mysql\n username: root\n password: ${googlesecretmanager:projects/PROJECT_ID/secrets/SECRET_NAME/versions/VERSION}\n```\n\n### Restart the Ops Agent\n\n### Linux\n\n1. To restart the agent, run the following command on your instance: \n\n ```\n sudo systemctl restart google-cloud-ops-agent\n ```\n2. To confirm that the agent restarted, run the following command and verify that the components \"Metrics Agent\" and \"Logging Agent\" started: \n\n ```\n sudo systemctl status \"google-cloud-ops-agent*\"\n ```\n\n### Windows\n\n1. Connect to your instance using RDP or a similar tool and login to Windows.\n2. Open a PowerShell terminal with administrator privileges by right-clicking the PowerShell icon and selecting **Run as Administrator**\n3. To restart the agent, run the following PowerShell command: \n\n ```\n Restart-Service google-cloud-ops-agent -Force\n ```\n4. To confirm that the agent restarted, run the following command and verify that the components \"Metrics Agent\" and \"Logging Agent\" started: \n\n ```\n Get-Service google-cloud-ops-agent*\n ```"]]