Your Gemini API key works in a local Python script. Then you move the project to another computer, a Docker container, or a GitHub Actions workflow—and suddenly authentication fails.
Sometimes the problem is simple: the new process cannot see GEMINI_API_KEY. Other times, the application works but the credential has accidentally been exposed in a repository, container configuration, or deployment log.
I've found that the safest setup is also one of the easiest to maintain: keep the key outside application code, inject it into the environment that needs it, and verify that the running process can access it without printing the secret.
This guide covers practical Gemini API key management on Windows, Linux, Docker, and CI/CD pipelines. It assumes you already have a working Gemini Developer API key.
ON THIS PAGE
Why Use Environment Variables for Gemini API Keys?
Set GEMINI_API_KEY on Windows
Configure Gemini API Keys on Linux
Manage Gemini API Keys in Docker
Secure Gemini API Keys in CI/CD
Verify Your Environment Configuration
Prevent Key Leaks and Rotate Credentials
Common Configuration Problems
Frequently Asked Questions
Why Use Environment Variables for Gemini API Keys?
The most common mistake in an early Gemini project is putting the API key directly into application code.
For example, this approach is unsafe:
from google import genai
client = genai.Client(
api_key="YOUR_ACTUAL_API_KEY"
)If the file is committed to GitHub, shared with a collaborator, or included in a deployment package, the credential may become exposed.
An environment variable provides a cleaner separation between the application and its configuration.
Instead of embedding the key, Python can read it at runtime:
import os
api_key = os.environ["GEMINI_API_KEY"]This has several advantages:
The same application code can run in different environments.
Credentials can be replaced without editing source files.
Development and production can use different keys.
CI/CD platforms can inject credentials during execution.
Developers are less likely to commit keys accidentally.
However, environment variables are not encrypted secret storage.
Depending on the operating system and deployment configuration, they may be visible to privileged users, debugging tools, or process inspection utilities.
For local development, environment variables are often sufficient. For production, a managed secret store is generally a better starting point.
Set GEMINI_API_KEY on Windows
Windows developers typically use PowerShell or Command Prompt.
Both can configure environment variables, but the commands and persistence behavior differ.
Option 1: Set the Key in PowerShell
Open PowerShell and run:
$env:GEMINI_API_KEY = "YOUR_API_KEY"This makes the key available to processes launched from the current PowerShell session.
For example, a Python script started from that terminal can read it.
The variable disappears when the session ends.
This is convenient for short experiments, although entering a real key directly into a command can leave it in shell history.
For a safer interactive approach, use a secure prompt:
$secure = Read-Host "Gemini API Key" -AsSecureString
$ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
try {
$env:GEMINI_API_KEY = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr)
}
finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr)
Remove-Variable secure, ptr -ErrorAction SilentlyContinue
}This avoids placing the literal key in the command itself. The resulting environment variable is still accessible as plaintext to the running process.
Option 2: Set the Key in Command Prompt
For a temporary CMD session:
set GEMINI_API_KEY=YOUR_API_KEYApplications started from that Command Prompt can access the variable.
Like the PowerShell example, the value is not automatically preserved for future sessions.
Avoid typing actual credentials into terminals that record command history or session output.
Option 3: Configure a Persistent Windows Variable
Windows supports persistent user environment variables.
You can configure them through:
System Properties → Advanced → Environment Variables
Add a user variable with the following name:
GEMINI_API_KEY
Enter the credential as its value.
New terminal sessions should inherit the updated setting.
Be aware that a persistent user environment variable is not a secure vault. Other software running under the same user context may be able to access it.
For sensitive production credentials, use a dedicated secret-management solution.
Verify the Windows Configuration
Instead of printing the key, use Python:
import os
print(
"Configured"
if os.getenv("GEMINI_API_KEY")
else "Missing"
)If the result is Configured, the Python process can see a nonempty value.
That does not prove the credential is valid, but it confirms the environment variable is available.

Configure Gemini API Keys on Linux
Linux environments commonly use Bash or another compatible shell.
The main distinction is whether the variable exists only in the current session or is loaded for future sessions.
Set a Temporary Environment Variable
In Bash:
export GEMINI_API_KEY="YOUR_API_KEY"Programs launched from that shell can access the variable.
This is useful for temporary local testing, but entering a real key in the command may expose it through shell history.
A better interactive pattern is:
read -rsp "Gemini API Key: " GEMINI_API_KEY
echo
export GEMINI_API_KEYThe -s option prevents the entered value from being displayed.
The key remains available in the shell environment until it is removed or the session ends.
Configure Persistent Local Development
For repeated development, some developers add environment variables directly to .bashrc or .profile.
However, placing plaintext credentials in shell startup files is not my preferred approach.
A more maintainable option is to use a local .env file that is excluded from version control.
Example:
GEMINI_API_KEY=YOUR_API_KEYAdd the following entry to .gitignore:
.env
.env.*
!.env.exampleThe .env.example file can document required variable names without including real credentials.
For example:
GEMINI_API_KEY=A .env file is not automatically loaded by every Linux process.
If your application uses Python, you can explicitly load it with python-dotenv:
python -m pip install python-dotenvimport os
from dotenv import load_dotenv
load_dotenv()
api_key = os.environ["GEMINI_API_KEY"]Keep the real .env file outside version control and restrict filesystem access appropriately.
On a single-user Linux development machine, this can be a practical solution. It should not be mistaken for encrypted credential storage.
Manage Gemini API Keys in Docker
Docker introduces another configuration boundary.
An environment variable available on your laptop is not automatically available inside a container.
You must explicitly provide the credential to the container or configure a secret-delivery mechanism.
Option 1: Pass an Existing Environment Variable
If GEMINI_API_KEY is already set in your shell, you can pass it to a container:
docker run --rm \
-e GEMINI_API_KEY \
my-gemini-appThis instructs Docker to pass the current variable value into the container.
The application can then read it through the normal environment interface.
However, environment variables may be exposed through container metadata, debugging interfaces, or privileged inspection.
Use this approach only when its security limitations are acceptable.
Option 2: Use an Environment File
Create a local file named .env:
GEMINI_API_KEY=YOUR_API_KEYRun the container:
docker run --rm \
--env-file .env \
my-gemini-appThis avoids embedding the key in the Docker command itself.
However, the file still contains a plaintext secret.
Do not commit it to Git or include it in the Docker image.
Option 3: Use Docker Compose
For a simple development setup:
services:
gemini-app:
image: my-gemini-app
env_file:
- .envThis injects values from the local environment file into the container.
It is convenient, but it does not provide the same protection as a dedicated secret store.
Option 4: Use Docker Secrets
For environments that support Docker secrets, sensitive values can be delivered as mounted files rather than ordinary environment variables.
For example, a Compose configuration can define a file-backed secret:
services:
gemini-app:
image: my-gemini-app
secrets:
- gemini_api_key
secrets:
gemini_api_key:
file: ./secrets/gemini_api_key.txtInside the container, the application can read the secret file:
from pathlib import Path
api_key = Path(
"/run/secrets/gemini_api_key"
).read_text().strip()Keep the source secret file out of Git.
Docker Compose file-backed secrets and Docker Swarm secrets have different storage and security characteristics. A local Compose secret file should not be assumed to provide encrypted secret storage.
For production, use the secret-management capabilities supported by your orchestration platform.

Secure Gemini API Keys in CI/CD
A deployment pipeline should not contain real API keys in workflow source files.
Instead, use the CI/CD provider's dedicated secret store.
GitHub Actions is a useful example.
Step 1: Add a GitHub Actions Secret
Open your repository on GitHub.
Navigate to:
Settings → Secrets and variables → Actions
Create a repository secret named:
GEMINI_API_KEY
Paste the actual key into the secret value field.
For production deployments, consider environment-scoped secrets with appropriate approval and access restrictions.
Step 2: Reference the Secret in a Workflow
A minimal GitHub Actions example:
name: Gemini Configuration Check
on:
workflow_dispatch:
jobs:
verify:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Verify Gemini key availability
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
run: |
python -c "import os; assert os.getenv('GEMINI_API_KEY'), 'Missing Gemini API key'; print('Gemini key configured')"The workflow checks whether the secret is available without printing its value.
This example intentionally does not make an API request.
It verifies secret injection, not model access or quota.
Step 3: Restrict Secret Access
Not every workflow needs access to your Gemini credential.
Apply the following practices:
Provide secrets only to jobs that require them.
Avoid exposing production secrets to untrusted pull requests.
Use protected deployment environments where appropriate.
Avoid printing environment variables in debugging output.
Limit repository and workflow modification permissions.
Review third-party actions before granting them access to secrets.
GitHub's log masking is useful, but it should not be treated as a guarantee that every transformed or partially printed secret will be hidden.
What About Other CI/CD Platforms?
The same principle applies to GitLab CI/CD, Jenkins, and other systems.
Store the credential in the platform's protected credential store, inject it only into authorized jobs, and avoid putting the value directly in pipeline configuration.
For example, Jenkins provides credential-binding mechanisms that can expose a secret to a specific build step.
The important distinction is between a credential managed by the CI/CD platform and a plaintext value committed to the pipeline repository.
Verify Your Environment Configuration
Once the environment variable is configured, verify it from the process that will actually run your application.
A reliable test should avoid displaying the credential.
Create check_env.py:
import os
import sys
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
print("ERROR: GEMINI_API_KEY is missing")
sys.exit(1)
print("GEMINI_API_KEY is configured")Run:
python check_env.pyA successful result means the variable is present and nonempty.
If it fails, check the execution environment rather than immediately replacing the API key.
For example, a variable set in a Windows terminal may not be available to a separately launched IDE.
Likewise, a variable configured on the Docker host will not automatically appear inside a container unless it is explicitly injected.
Prevent Key Leaks and Rotate Credentials
Environment variables reduce accidental hardcoding, but they do not eliminate credential exposure risks.
The most useful security habits are the ones that remain practical during everyday development.
Keep Secrets Out of Git
Before committing, inspect the files being tracked:
git statusCheck whether a sensitive file is already tracked:
git ls-files .envIf a secret was previously committed, adding .env to .gitignore will not remove it from repository history.
Treat the credential as potentially exposed and rotate it.
Avoid Logging Credentials
Do not print the complete environment or exception details that may contain credentials.
Avoid commands that dump all environment variables into CI logs.
When troubleshooting, check only whether the required variable exists.
Rotate Exposed Keys
When a Gemini API key is suspected to be compromised:
Create a replacement credential.
Update the relevant local, container, and CI/CD configurations.
Verify that applications can use the replacement.
Revoke the exposed credential promptly.
Review usage and billing activity for unexpected requests.
For an actively abused key, immediate revocation may be necessary even if it temporarily interrupts the application.
Use Managed Secrets for Production
For production applications, consider Google Cloud Secret Manager or the equivalent service in your hosting platform.
A managed secret store can provide access controls, audit logging, and integration with workload identities.
If your deployment runs on Google Cloud, consider whether a supported identity-based authentication approach is more appropriate than distributing a long-lived API key.
The goal is to reduce the number of places where sensitive credentials must be copied and maintained.
Common Configuration Problems
Problem | Likely cause | Recommended fix |
|---|---|---|
Variable works in one terminal but not another | Session-scoped configuration | Set it in the correct session or configure an appropriate persistent source |
Python reports a missing key | Variable was not inherited or | Check process environment and loading code |
Docker container cannot read the key | Host variable was not injected | Configure |
GitHub Actions reports a missing secret | Secret is unavailable to the job | Check name, scope, environment, and workflow permissions |
Key appears in Git history | Secret was committed previously | Rotate the key and address repository history |
Variable exists but Gemini rejects the request | Credential, restriction, model, or quota problem | Check the API error and project configuration |
A useful debugging rule is to separate two questions:
Can the process read the key?
Can the key successfully authenticate an API request?
Environment configuration solves the first question. A valid credential, supported model, and available quota determine the second.
Frequently Asked Questions
What environment variable does the Gemini API use?
GEMINI_API_KEY is the commonly used environment variable for Gemini Developer API applications and SDK examples.
Some Google Gen AI SDK configurations also recognize GOOGLE_API_KEY. Avoid setting conflicting values without understanding the SDK's precedence behavior.
Is storing a Gemini API key in an environment variable safe?
It is generally safer than hardcoding the key in source code, but it is not equivalent to encrypted secret storage.
Security depends on the operating system, process permissions, deployment platform, and logging practices.
Should I put GEMINI_API_KEY in .bashrc?
You can, but a plaintext credential in a shell startup file is not ideal.
For local development, a protected .env file or a credential manager may be more maintainable.
For production, prefer managed secrets.
Does Docker automatically inherit GEMINI_API_KEY?
No. Docker containers do not automatically receive every environment variable from the host.
You must explicitly configure environment variable injection or secret delivery.
Can GitHub Actions use a Gemini API key?
Yes. Store the key as a GitHub Actions secret and reference it only in authorized workflow steps.
Do not put the real key directly into workflow YAML.
Should development and production share the same key?
Separate credentials are preferable because they make rotation, incident response, and usage investigation easier.
Where appropriate, separate projects can also improve quota and billing isolation.
Final Thoughts
Managing a Gemini API key becomes more complicated when an application moves beyond a single development script.
Windows and Linux require attention to shell sessions and persistent configuration. Docker adds a container boundary. CI/CD introduces workflow permissions, secret injection, and deployment controls.
My preferred rule is simple: the application should know where to read the credential, but the source code should never contain the credential itself.
For local experiments, environment variables and properly excluded .env files are practical tools.
For production systems, use managed secret storage, restricted access, and a tested rotation process.
I tried the lightweight approach first. The habits worth keeping are the ones that work across every environment without turning credential management into another application.