Definir variables de entorno de compilación (despliegue de origen)
Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
Las variables de entorno de compilación son pares clave-valor que le permiten transferir información de configuración a los paquetes de compilación al implementar desde el código fuente. Por ejemplo, en tiempo de compilación, puede que quieras personalizar las opciones del compilador, especificar certificados de tiempo de compilación, configurar parámetros, etc.
En esta página se muestra cómo definir variables de entorno de compilación que están disponibles en tiempo de compilación. Es relevante para los desarrolladores de plataformas que implementan servicios o funciones de Cloud Run desde el código fuente. Las marcas de la variable de entorno de compilación de la CLI de gcloud se admiten en las implementaciones de origen (--source), pero no en las implementaciones de imágenes de contenedor (--image).
Puedes usar variables de entorno para la configuración de servicios o funciones, pero no te recomendamos que las utilices para almacenar secretos, como credenciales de bases de datos o claves de API.
Almacena los valores sensibles fuera del código fuente y de las variables de entorno. Para almacenar secretos, te recomendamos que uses Secret Manager.
Para configurar los servicios que acceden a los secretos almacenados en Secret Manager, consulta Configurar secretos.
Antes de empezar
Habilita las APIs Admin de Cloud Run y Cloud Build:
Una vez que se haya habilitado la API Cloud Run Admin, se creará automáticamente la cuenta de servicio predeterminada de Compute Engine.
Roles obligatorios
Tú o tu administrador debéis conceder los siguientes roles de gestión de identidades y accesos a la cuenta de implementación y a la cuenta de servicio de Cloud Build.
Haz clic para ver los roles necesarios de la cuenta de implementación
Para obtener los permisos que necesitas para compilar e implementar desde la fuente, pide a tu administrador que te conceda los siguientes roles de gestión de identidades y accesos:
Haz clic para ver los roles necesarios de la cuenta de servicio de Cloud Build
Cloud Build usa automáticamente la cuenta de servicio predeterminada de Compute Engine como cuenta de servicio predeterminada de Cloud Build para compilar tu código fuente y tu recurso de Cloud Run, a menos que anules este comportamiento. Para que Cloud Build compile tus fuentes, pide a tu administrador que conceda el rol Compilador de Cloud Run (roles/run.builder) a la cuenta de servicio predeterminada de Compute Engine de tu proyecto:
Sustituye PROJECT_NUMBER por el número de tu proyecto Google Cloud
y PROJECT_ID por el ID de tu proyecto Google Cloud. Para obtener instrucciones detalladas sobre cómo encontrar el ID y el número de tu proyecto, consulta el artículo Crear y gestionar proyectos.
La concesión del rol de compilador de Cloud Run a la cuenta de servicio predeterminada de Compute Engine tarda un par de minutos en propagarse.
SERVICE con el nombre de tu servicio de Cloud Run.
KEY1=VALUE1,KEY2=VALUE2 con la lista de nombres de variables y sus valores separados por comas que se implementan junto con una función que te permite transferir información de configuración a los buildpacks.
Si vas a desplegar una función, añade la marca --function con el punto de entrada de la función de tu código fuente.
Actualizar variables de entorno de compilación
Puedes actualizar las variables de entorno de compilación de los servicios que ya tengas. Se trata de un enfoque no destructivo que cambia o añade variables de entorno de compilación, pero no las elimina.
gcloud
Para actualizar las variables de entorno de compilación de los servicios, usa la marca --update-build-env-vars:
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-21 (UTC)."],[],[],null,["# Set build environment variables (source deploy)\n\nBuild environment variables are key-value pairs that let you pass configuration\ninformation to [buildpacks](/docs/buildpacks/overview) when deploying\nfrom source code. For example, at build time, you might want to customize\ncompiler options, specify build-time certificates, configure parameters, and so\nforth.\n\nThis page shows how to set build environment variables that are available at\nbuild time, and is relevant for platform developers who are deploying\nCloud Run [services](/run/docs/deploying-source-code) or\n[functions](/run/docs/deploy-functions) from source. The build environment\nvariable gcloud CLI flags are supported for\n[source deployments](/run/docs/deploying-source-code) (`--source`), and not\nsupported for [container image deployments](/run/docs/deploying) (`--image`).\n\nYou can use environment variables for service or function configuration, but we don't\nrecommend them as a way to store secrets such as database credentials or API keys.\nStore sensitive values outside both your source code and environment variables. To\nstore secrets, we recommend using Secret Manager.\nTo configure services that access secrets stored in Secret Manager,\nsee [Configure secrets](/run/docs/configuring/secrets).\n\nBefore you begin\n----------------\n\n- Enable the Cloud Run Admin API and the Cloud Build API:\n\n ```bash\n gcloud services enable run.googleapis.com \\\n cloudbuild.googleapis.com\n ```\n\n After the Cloud Run Admin API is enabled, the Compute Engine default service account is\n automatically created.\n\n### Required roles\n\nYou or your administrator must grant the deployer account and the\nCloud Build service account the following IAM roles. \n\n#### Click to view required roles for the deployer account\n\nTo get the permissions that you need to build and deploy from source,\nask your administrator to grant you the following IAM\nroles:\n\n- [Cloud Run Source Developer](/iam/docs/understanding-roles#run.sourceDeveloper) (`roles/run.sourceDeveloper`) on your project\n- [Service Usage Consumer](/iam/docs/understanding-roles#serviceusage.serviceUsageConsumer) (`roles/serviceusage.serviceUsageConsumer`) on your project\n- [Service Account User](/iam/docs/understanding-roles#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`) on the Cloud Run service identity \n\n#### Click to view required roles for the Cloud Build service account\n\nCloud Build automatically uses the\n[Compute Engine default service\naccount](/build/docs/cloud-build-service-account) as the default Cloud Build service account to build your source code and\nCloud Run resource, unless you override this behavior. For\nCloud Build to build your sources, ask your administrator to grant\n[Cloud Run Builder](/iam/docs/understanding-roles#run.builder)\n(`roles/run.builder`) to the Compute Engine default\nservice account on your project: \n\n```bash\n gcloud projects add-iam-policy-binding PROJECT_ID \\\n --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \\\n --role=roles/run.builder\n \n```\n\nReplace \u003cvar translate=\"no\"\u003ePROJECT_NUMBER\u003c/var\u003e with your Google Cloud\nproject number, and \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with your Google Cloud\nproject ID. For detailed instructions on how to find your project ID, and project number,\nsee [Creating\nand managing projects](/resource-manager/docs/creating-managing-projects#identifying_projects).\n\nGranting the Cloud Run builder role to the Compute Engine default service account\ntakes a couple of minutes to [propagate](/iam/docs/access-change-propagation).\n| **Note:**\n|\n|\n| The [`iam.automaticIamGrantsForDefaultServiceAccounts` organization policy constraint](/resource-manager/docs/organization-policy/restricting-service-accounts#disable_service_account_default_grants)\n| prevents the Editor role from being automatically granted to default service accounts. If you\n| created your organization after May 3, 2024, this constraint is enforced by\n| default.\n|\n|\n| We strongly recommend that you enforce this constraint to disable the automatic role grant. If you\n| disable the automatic role grant, you must decide which roles to grant to the default service\n| accounts, and then [grant these roles](/iam/docs/granting-changing-revoking-access)\n| yourself.\n|\n|\n| If the default service account already has the Editor role, we recommend that you replace the\n| Editor role with less permissive roles.To safely modify the service account's roles, use [Policy Simulator](/policy-intelligence/docs/simulate-iam-policies) to see the impact of\n| the change, and then [grant and revoke the\n| appropriate roles](/iam/docs/granting-changing-revoking-access).\n\nFor a list of IAM roles and permissions that are associated with\nCloud Run, see\n[Cloud Run IAM roles](/run/docs/reference/iam/roles)\nand [Cloud Run IAM permissions](/run/docs/reference/iam/permissions).\nIf your Cloud Run service interfaces with\nGoogle Cloud APIs, such as Cloud Client Libraries, see the\n[service identity configuration guide](/run/docs/configuring/services/service-identity).\nFor more information about granting roles, see\n[deployment permissions](/run/docs/reference/iam/roles#additional-configuration)\nand [manage access](/iam/docs/granting-changing-revoking-access).\n\nMaximum number of build environment variables and limits\n--------------------------------------------------------\n\nYou can define up to 100 build environment\nvariables, with a total key and value limit of 64 KiB.\n\nSet build environment variables\n-------------------------------\n\nYou can set build environment variables to establish new variables or completely\nreplace existing build variables.\n**Note:** Keys must start with an uppercase ASCII letter, and consist of uppercase ASCII letters, digits, and underscores. You should avoid creating variable keys with a `GOOGLE_*` prefix. [View all supported buildpacks environment variables](/docs/buildpacks/service-specific-configs). \n\n### gcloud\n\nTo set build environment variables when deploying a service from\nsource code, use the `--set-build-env-vars` flag: \n\n```bash\ngcloud run deploy SERVICE \\\n --source . \\\n --set-build-env-vars KEY1=VALUE1,KEY2=VALUE2\n```\n\nReplace:\n\n- \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with name of your Cloud Run service.\n- \u003cvar translate=\"no\"\u003eKEY1=VALUE1,KEY2=VALUE2\u003c/var\u003e with the comma-separated list of variable names and their values that are deployed alongside a function that let you pass configuration information to buildpacks.\n\nIf you are deploying a function, add the `--function` flag with the function\nentry point from your source code.\n\nUpdate build environment variables\n----------------------------------\n\nYou can update build environment variables for existing services. This is a\nnon-destructive approach that changes or adds build environment variables, but\ndoes not delete the build environment variables. \n\n### gcloud\n\nTo update build environment variables for existing services, use the\n`--update-build-env-vars` flag: \n\n```bash\ngcloud run deploy SERVICE \\\n --source . \\\n --update-build-env-vars KEY1=VALUE1,KEY2=VALUE2\n```\n\nIf you are deploying a function, add the `--function` flag with the function\nentry point from your source code.\n\nDelete build environment variables\n----------------------------------\n\nYou can delete build environment variables for existing services. \n\n### gcloud\n\nTo remove build environment variables for existing services, use the\n`--remove-build-env-vars` flag: \n\n```bash\ngcloud run deploy SERVICE \\\n --source . \\\n --remove-build-env-vars KEY1=VALUE1,KEY2=VALUE2\n```\n\nAlternatively, you can clear build environment variables by using the\n`--clear-build-env-vars` for existing services: \n\n```bash\ngcloud run deploy SERVICE \\\n --source . \\\n --clear-build-env-vars KEY1=VALUE1,KEY2=VALUE2\n```\n\nIf you are deploying a function, add the `--function` flag with the function\nentry point from your source code.\n\nUse a build environment variables file\n--------------------------------------\n\nYou can use a build environment variables file for existing functions. \n\n### gcloud\n\nTo set build environment variables from a file, use the\n`--build-env-vars-file` flag: \n\n```bash\ngcloud run deploy SERVICE \\\n --source . \\\n --build-env-vars-file FILE_NAME.yaml\n```\n\nReplace \u003cvar translate=\"no\"\u003eFILE_NAME\u003c/var\u003e.yaml where the contents of the file, which\nshould look as follows: \n\n KEY1: VALUE1\n KEY2: VALUE2\n\nIf you are deploying a function, add the `--function` flag with the function\nentry point from your source code."]]