Keeping secrets out of your code Beginner
API keys and passwords are like house keys. If they end up inside your code or a chat, anyone who sees it can get in. Here's how to keep them safe.
What you'll learn
- What counts as a secret
- Using environment variables
- What to do if a secret leaks
Before you start
- The Grok Bot app, installed and signed in. New? See where to download it and installing and signing in.
- A small script or bot project (for example the one from Your First Bot).
1. What counts as a secret
API keys, tokens, passwords, client secrets and webhook signing secrets. If it lets someone act as you, it's a secret. (New to keys? See API keys vs OAuth.)
2. Why not just type it into the code?
Code gets copied, shared, uploaded to GitHub and pasted into chats. A key written in the code travels with it. People scan public code for leaked keys.
3. Use an environment variable
An environment variable is a named value your computer hands to a program when it runs, kept outside the code.
- Set it in your terminal:
export WEATHER_API_KEY="your-key"(macOS/Linux) orsetx WEATHER_API_KEY "your-key"(Windows, then open a new terminal). - Read it in Python:
import osthenkey = os.environ["WEATHER_API_KEY"]. - Optionally keep a
.envfile for local use, and add.envto your.gitignoreso it never gets uploaded.
4. With Grok Bot
When your bot needs a secret, let it ask with a secure form: the field is masked and the value isn't written into the chat or shown to the bot. Logins and cards belong in the Vault (see Safety and approvals). Never paste a secret into ordinary chat.
5. If a secret leaks
- Go to the service and revoke or regenerate (rotate) the key right away.
- Update your environment variable with the new one.
- Check the service's activity log for anything odd.
Ideas to try
- Weekend coder.
Look at my script and move every hard-coded key into environment variables.
- Before sharing.
Scan this folder for anything that looks like a secret before I upload it to GitHub.
- Oops moment.
I pasted my store API key in an email. Walk me through rotating it.
- Setting up.
Create a .gitignore for my Python project that keeps .env files out.
Tips
- Use a different key for testing and for real use.
- Give each key the fewest permissions possible.
- Rotate keys now and then, not only after leaks.
Facts about the Grok Bot app come from Cursor's official Grok Bot documentation. See Python docs: os.environ and GitHub: about secret scanning. Menus and services change; if something looks different, check the official docs or ask your bot.