env-config
Environment configuration and secrets management skill using UV for Python projects. Handles .env files, environment variables, secrets encryption, multi-environment setups, and secure configuration patterns. Use when setting up project environments, managing API keys, or implementing configuration best practices.
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o env-config.zip https://jpskill.com/download/17358.zip && unzip -o env-config.zip && rm env-config.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17358.zip -OutFile "$d\env-config.zip"; Expand-Archive "$d\env-config.zip" -DestinationPath $d -Force; ri "$d\env-config.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
env-config.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
env-configフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 7
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
環境設定 Skill
概要
この Skill は、UV (最新の Python パッケージおよびプロジェクトマネージャー) を使用した Python プロジェクトにおける環境設定、シークレット、および環境変数の管理に関する包括的なガイダンスを提供します。セキュアな設定パターン、マルチ環境のセットアップ、.env ファイルの管理、および暗号化サポートによるシークレットの処理について説明します。
環境設定は、設定をコードから分離し (12-factor app の原則)、環境全体でシークレットを安全に管理し、認証情報の漏洩を防ぎ、チームのコラボレーションをサポートするために重要です。
この Skill を使用する場面
この Skill は、以下が必要な場合に使用します。
- 新しい Python プロジェクトの環境設定をセットアップする
- セキュアなシークレット管理を実装する
- マルチ環境のセットアップ (dev/staging/prod) を構成する
- ハードコードされた設定から環境変数に移行する
- 既存の設定にセキュリティ上の問題がないか監査する
- チームプロジェクト全体で設定を標準化する
- 適切な設定管理を備えた UV ベースの Python プロジェクトをセットアップする
中核となる原則
1. シークレットをハードコードしない
- すべての API キー、パスワード、トークンは、環境変数または暗号化されたシークレットに格納する
- シークレットを含む設定ファイルは、.gitignore に含める必要がある
- 実際のシークレットではなく、構造を共有するためのテンプレートを使用する
2. 環境ごとに分離する
- 開発、ステージング、本番環境で異なる設定を使用する
- 環境固有の .env ファイル (.env.development, .env.production) を使用する
- 環境変数には明確な命名規則を使用する
3. 安全に失敗する
- 起動時に必要な環境変数を検証する
- 設定が見つからない場合は、明確なエラーメッセージを表示する
- 機密性の低い値に対してのみ、適切なデフォルト値を使用する
4. 依存関係の管理に UV を使用する
- UV は、高速で信頼性の高い Python パッケージ管理を提供する
- pip、pip-tools、virtualenv などを置き換える
- マシン間で再現可能な環境を保証する
5. すべてを文書化する
- テンプレートファイルは、シークレットを公開せずに構造を示す
- README は、必要な変数とその設定方法を説明する
- コメントは、変数の目的と形式を記述する
UV のセットアップ
UV のインストール
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# または pip で
pip install uv
# インストールを確認
uv --version
UV プロジェクトの初期化
# 新しいプロジェクトを作成
uv init my-project
cd my-project
# 仮想環境を作成
uv venv
source .venv/bin/activate # Windows の場合: .venv\Scripts\activate
# 依存関係を追加
uv add python-dotenv cryptography pydantic
# 開発依存関係を追加
uv add --dev pytest pytest-env black ruff
環境設定のワークフロー
フェーズ 1: プロジェクトのセットアップ
1. プロジェクト構造の作成
# UV プロジェクトを初期化
uv init your-project-name
cd your-project-name
uv venv
source .venv/bin/activate
2. 設定依存関係のインストール
uv add python-dotenv # .env ファイルのロード用
uv add cryptography # シークレットの暗号化用 (オプション)
uv add pydantic # 設定の検証用 (オプション)
uv add --dev pytest pytest-env
3. 設定ファイルの作成
作成する必要がある重要なファイル:
.env.template- 必要な変数を示すテンプレート (これをコミットする).env- 実際のシークレット (これを .gitignore に追加する).env.development- 開発環境固有の設定.env.production- 本番環境固有の設定config.py- 設定ロードモジュール
4. .gitignore の更新
# .gitignore に追加
cat >> .gitignore << 'EOF'
# 環境ファイル
.env
.env.local
.env.*.local
secrets.json
# UV
.venv/
__pycache__/
*.pyc
.pytest_cache/
.ruff_cache/
EOF
フェーズ 2: 設定テンプレートの作成
1. .env.template の作成
# .env.template - このファイルをコミットする
# .env にコピーして、実際の値を入力する
# アプリケーション設定
APP_NAME=MyApp
APP_ENV=development
DEBUG=true
LOG_LEVEL=INFO
# データベース設定
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
DATABASE_POOL_SIZE=5
# API キー (実際のキーに置き換える)
ANTHROPIC_API_KEY=sk-ant-api03-xxx
OPENAI_API_KEY=sk-xxx
OPENROUTER_API_KEY=sk-or-v1-xxx
# セキュリティ
SECRET_KEY=generate-random-secret-key-here
JWT_SECRET=another-random-secret
# 機能フラグ
ENABLE_ANALYTICS=false
ENABLE_CACHING=true
2. 設定ロードモジュールの作成
config.py を作成 - 完全な実装については references/api-reference.md を参照してください:
import os
from pathlib import Path
from dotenv import load_dotenv
class ConfigError(Exception):
"""必要な設定が見つからない場合に発生します。"""
pass
class Config:
"""環境変数からのアプリケーション設定。"""
def __init__(self, env: str = None):
self.env = env or os.getenv('APP_ENV', 'development')
self._load_env_file()
self._validate_required()
def _load_env_file(self):
"""環境に基づいて適切な .env ファイルをロードします。"""
env_file = Path(f'.env.{self.env}')
if env_file.exists():
load_dotenv(env_file, override=True)
if Path('.env').exists():
load_dotenv('.env', override=False)
@property
def app_name(self) -> str:
return os.getenv('APP_NAME', 'MyApp')
@property
def debug(self) -> bool:
return os.getenv('DEBUG', 'false').lower() in ('true', '1', 'yes')
# 必要に応じてプロパティを追加...
# グローバルな config インスタンス
config = Config()
すべてのプロパティと検証を含む完全な Config クラスについては、references/api-reference.md を参照してください。
3. アプリケーションで Config を使用する
from config import config
def main():
print(f"Starting {config.app_name} in {config.app_env} mode")
if config.anthropic_api_key:
# API キーを使用
print("✓ API key loaded")
フェーズ 3: マルチ環境のセットアップ
1. 環境固有のファイルを作成する
.env.development:
APP_ENV=development
DEBUG=true
LOG_LEVEL=DEBUG
DATABASE_URL=postgresql://localhost:5432/myapp_dev
.env.production:
APP_ENV=production
DEBUG=false
LOG_LEVEL=WARNING
DATABA 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Environment Configuration Skill
Overview
This skill provides comprehensive guidance for managing environment configurations, secrets, and environment variables in Python projects using UV (the modern Python package and project manager). It covers secure configuration patterns, multi-environment setups, .env file management, and secrets handling with encryption support.
Environment configuration is critical for separating configuration from code (12-factor app principles), managing secrets securely across environments, preventing credential leaks, and supporting team collaboration.
When to Use This Skill
Use this skill when you need to:
- Set up environment configuration for a new Python project
- Implement secure secrets management
- Configure multi-environment setups (dev/staging/prod)
- Migrate from hardcoded configs to environment variables
- Audit existing configuration for security issues
- Standardize configuration across team projects
- Set up UV-based Python project with proper config management
Core Principles
1. Never Hardcode Secrets
- All API keys, passwords, tokens go in environment variables or encrypted secrets
- Configuration files with secrets must be in .gitignore
- Use templates for sharing structure, not actual secrets
2. Separate by Environment
- Different configurations for development, staging, production
- Environment-specific .env files (.env.development, .env.production)
- Clear naming conventions for environment variables
3. Fail Securely
- Validate required environment variables on startup
- Provide clear error messages for missing configuration
- Use sensible defaults only for non-sensitive values
4. Use UV for Dependency Management
- UV provides fast, reliable Python package management
- Replaces pip, pip-tools, virtualenv, and more
- Ensures reproducible environments across machines
5. Document Everything
- Template files show structure without exposing secrets
- README explains required variables and how to set them
- Comments describe purpose and format of variables
UV Setup
Installing UV
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Or with pip
pip install uv
# Verify installation
uv --version
Initialize UV Project
# Create new project
uv init my-project
cd my-project
# Create virtual environment
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Add dependencies
uv add python-dotenv cryptography pydantic
# Add dev dependencies
uv add --dev pytest pytest-env black ruff
Environment Configuration Workflow
Phase 1: Project Setup
1. Create Project Structure
# Initialize UV project
uv init your-project-name
cd your-project-name
uv venv
source .venv/bin/activate
2. Install Configuration Dependencies
uv add python-dotenv # For .env file loading
uv add cryptography # For secrets encryption (optional)
uv add pydantic # For config validation (optional)
uv add --dev pytest pytest-env
3. Create Configuration Files
Essential files to create:
.env.template- Template showing required variables (commit this).env- Actual secrets (add to .gitignore).env.development- Development-specific config.env.production- Production-specific configconfig.py- Configuration loading module
4. Update .gitignore
# Add to .gitignore
cat >> .gitignore << 'EOF'
# Environment files
.env
.env.local
.env.*.local
secrets.json
# UV
.venv/
__pycache__/
*.pyc
.pytest_cache/
.ruff_cache/
EOF
Phase 2: Create Configuration Templates
1. Create .env.template
# .env.template - Commit this file
# Copy to .env and fill in actual values
# Application Settings
APP_NAME=MyApp
APP_ENV=development
DEBUG=true
LOG_LEVEL=INFO
# Database Configuration
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
DATABASE_POOL_SIZE=5
# API Keys (Replace with actual keys)
ANTHROPIC_API_KEY=sk-ant-api03-xxx
OPENAI_API_KEY=sk-xxx
OPENROUTER_API_KEY=sk-or-v1-xxx
# Security
SECRET_KEY=generate-random-secret-key-here
JWT_SECRET=another-random-secret
# Feature Flags
ENABLE_ANALYTICS=false
ENABLE_CACHING=true
2. Create Config Loading Module
Create config.py - see references/api-reference.md for complete implementation:
import os
from pathlib import Path
from dotenv import load_dotenv
class ConfigError(Exception):
"""Raised when required configuration is missing."""
pass
class Config:
"""Application configuration from environment variables."""
def __init__(self, env: str = None):
self.env = env or os.getenv('APP_ENV', 'development')
self._load_env_file()
self._validate_required()
def _load_env_file(self):
"""Load appropriate .env file based on environment."""
env_file = Path(f'.env.{self.env}')
if env_file.exists():
load_dotenv(env_file, override=True)
if Path('.env').exists():
load_dotenv('.env', override=False)
@property
def app_name(self) -> str:
return os.getenv('APP_NAME', 'MyApp')
@property
def debug(self) -> bool:
return os.getenv('DEBUG', 'false').lower() in ('true', '1', 'yes')
# Add more properties as needed...
# Global config instance
config = Config()
For complete Config class with all properties and validation, see references/api-reference.md.
3. Use Config in Application
from config import config
def main():
print(f"Starting {config.app_name} in {config.app_env} mode")
if config.anthropic_api_key:
# Use API key
print("✓ API key loaded")
Phase 3: Multi-Environment Setup
1. Create Environment-Specific Files
.env.development:
APP_ENV=development
DEBUG=true
LOG_LEVEL=DEBUG
DATABASE_URL=postgresql://localhost:5432/myapp_dev
.env.production:
APP_ENV=production
DEBUG=false
LOG_LEVEL=WARNING
DATABASE_URL=postgresql://prod-host:5432/myapp_prod
SECRET_KEY=super-secure-random-key
2. Switch Between Environments
# Development (default)
uv run python main.py
# Production
export APP_ENV=production
uv run python main.py
Phase 4: Secrets Management
1. Using JSON Secrets (Alternative Pattern)
Create secrets_template.json:
{
"anthropic_api_key": "sk-ant-api03-xxx",
"openai_api_key": "sk-xxx",
"database_password": "your-password-here",
"comment": "Copy to secrets.json and fill in real values"
}
2. Load JSON Secrets
See references/api-reference.md for complete implementation:
import json
from pathlib import Path
def load_secrets(secrets_file: str = 'secrets.json') -> dict:
"""Load secrets from JSON with fallback to env vars."""
if Path(secrets_file).exists():
return json.load(open(secrets_file))
# Fallback to environment variables
return {
'anthropic_api_key': os.getenv('ANTHROPIC_API_KEY', '')
}
3. Encrypted Secrets
For encryption utilities and advanced secrets management, see:
references/advanced-topics.md- Encryption, rotation, auditingscripts/env_helper.py- Encryption/decryption utilities
Configuration Validation
Using Pydantic for Type-Safe Config
from pydantic import BaseSettings, Field, validator
class Settings(BaseSettings):
app_name: str = Field(default='MyApp', env='APP_NAME')
app_env: str = Field(default='development', env='APP_ENV')
database_url: str = Field(..., env='DATABASE_URL') # Required
@validator('app_env')
def validate_env(cls, v):
allowed = ['development', 'staging', 'production']
if v not in allowed:
raise ValueError(f'app_env must be one of {allowed}')
return v
class Config:
env_file = '.env'
settings = Settings()
For complete Pydantic configuration examples, see references/api-reference.md.
Security Best Practices
1. .gitignore Configuration
Always add to .gitignore:
.env
.env.local
.env.*.local
secrets.json
.env.production
.venv/
2. Secret Rotation
Implement regular API key rotation:
def rotate_api_key(old_key: str, new_key: str):
"""Rotate API key gracefully with backup."""
# Implementation in references/advanced-topics.md
3. Environment Auditing
Regular security audits:
def audit_environment():
"""Check for security issues in environment variables."""
# Implementation in references/advanced-topics.md
For complete security implementations, see references/advanced-topics.md.
Testing Configuration
Basic Test Setup
# conftest.py
import pytest
import os
@pytest.fixture
def test_env():
"""Set up test environment variables."""
original = os.environ.copy()
os.environ['APP_ENV'] = 'testing'
os.environ['DEBUG'] = 'true'
yield
os.environ.clear()
os.environ.update(original)
@pytest.fixture
def config(test_env):
from config import Config
return Config(env='testing')
Example Tests
def test_config_loading(config):
assert config.app_env == 'testing'
assert config.debug is True
def test_missing_required_var():
from config import ConfigError
with pytest.raises(ConfigError):
Config() # Missing required vars
For comprehensive testing guide, see references/testing-guide.md.
UV Commands Reference
# Dependency management
uv sync # Install all dependencies
uv add requests # Add dependency
uv add --dev pytest # Add dev dependency
uv remove requests # Remove dependency
# Environment management
uv venv # Create virtual environment
uv lock --upgrade # Update dependencies
# Running scripts
uv run python main.py # Run with UV environment
uv run pytest # Run tests
# Compatibility
uv pip compile pyproject.toml -o requirements.txt
Helper Scripts
This skill provides utility scripts in scripts/:
env_helper.py- Core utilities for env management- Parse and validate .env files
- Check for missing variables
- Encrypt/decrypt secrets files
- Compare environments
- Generate .env templates
Usage:
# Validate .env file
python scripts/env_helper.py validate .env
# Encrypt secrets
python scripts/env_helper.py encrypt secrets.json secrets.encrypted
# Compare environments
python scripts/env_helper.py compare .env.development .env.production
Quick Reference
Setup Checklist
- [ ] Install UV:
curl -LsSf https://astral.sh/uv/install.sh | sh - [ ] Create project:
uv init project-name - [ ] Create virtual env:
uv venv - [ ] Add dependencies:
uv add python-dotenv - [ ] Create
.env.templatefrom examples - [ ] Copy to
.envand fill in secrets - [ ] Add
.envto.gitignore - [ ] Create
config.pymodule - [ ] Test configuration loading
- [ ] Set up environment-specific configs
- [ ] Implement validation
- [ ] Add tests for configuration
Environment Variable Naming
Use consistent naming:
APP_*- Application settingsDATABASE_*- Database configuration*_API_KEY- API keys and tokens*_SECRET- Secret keysENABLE_*- Feature flags*_URL- Service endpoints
Security Checklist
- [ ] No secrets in version control
- [ ]
.envin.gitignore - [ ] Production secrets separate from dev
- [ ] Required variables validated on startup
- [ ] Secrets encrypted at rest (if needed)
- [ ] Regular secret rotation
- [ ] Team training on secure practices
Additional Resources
Documentation in This Skill
references/api-reference.md- Complete Config class implementation, Pydantic validation, JSON secrets loadingreferences/advanced-topics.md- Encryption, secret rotation, auditing, multi-tenant config, cloud integrationreferences/testing-guide.md- pytest setup, mocking, validation testing, CI/CD examplesreferences/troubleshooting.md- Common issues, environment-specific problems, debugging techniques
Examples Directory
.env.example- Comprehensive .env templatepyproject.toml- UV project configurationsecrets_template.json- JSON secrets template
External Resources
- UV Documentation: https://docs.astral.sh/uv/
- python-dotenv: https://github.com/theskumar/python-dotenv
- Pydantic: https://docs.pydantic.dev/
- 12-Factor App Config: https://12factor.net/config
Troubleshooting
For common issues and solutions, see references/troubleshooting.md:
- Environment variables not loading
- Wrong environment loaded
- UV sync failures
- Import errors
- Secrets decryption issues
- Performance optimization
- Security issues and remediation
- Docker integration problems
Quick debug:
from dotenv import load_dotenv
load_dotenv(verbose=True) # Shows loading process 同梱ファイル
※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。
- 📄 SKILL.md (13,308 bytes)
- 📎 README.md (5,196 bytes)
- 📎 references/advanced-topics.md (10,428 bytes)
- 📎 references/api-reference.md (8,129 bytes)
- 📎 references/testing-guide.md (10,426 bytes)
- 📎 references/troubleshooting.md (11,396 bytes)
- 📎 scripts/env_helper.py (16,038 bytes)