Skip to main content

Production-ready Azure bootstrap library for App Configuration, Key Vault, and App Insights integration

Project description

Azure Bootstrap Library

Production-ready Azure bootstrap library for seamless integration of Azure App Configuration, Key Vault, and Application Insights into Azure Functions applications.

Python Version License Code Coverage CI/CD Pipeline

๐Ÿ“ฆ What is This Repository?

This repository contains the source code and build configuration for the azure-bootstrap pip library - a reusable bootstrap package used across 17+ Azure Functions repositories in the organization.

Package Name: azure-bootstrap Current Version: 1.0.0 Distribution: PyPI (public)

๐ŸŽฏ Purpose

This library solves the circular dependency problem between logging and configuration in Azure Functions:

  • Configuration loading needs logging โ†’ But logging needs configuration โ†’ ๐Ÿ”๐Ÿฅš
  • Our solution: 4-phase bootstrap that provides working logging throughout the entire process

What This Library Does

  1. Bootstrap Logging - Logging that works immediately, before configuration loaded
  2. Configuration Loading - Azure App Configuration with automatic Key Vault secret resolution
  3. Telemetry Setup - Application Insights with OpenTelemetry
  4. Environment Loading - All configs automatically loaded to os.environ with smart local overrides

๐Ÿ“‹ Table of Contents


๐Ÿš€ Quick Start

For Library Users

"""function_app.py"""
import os
import azure.functions as func
from azure_bootstrap import initialize_application, get_bootstrap_logger

_bootstrap_initialized = False
_logger = None

def _ensure_bootstrap():
    global _bootstrap_initialized, _logger
    if _bootstrap_initialized:
        return

    _logger = get_bootstrap_logger(__name__)
    config_repo = initialize_application()
    _bootstrap_initialized = True

app = func.FunctionApp()

@app.route(route="hello")
def hello(req):
    _ensure_bootstrap()
    db_host = os.getenv("DATABASE_HOST")  # All configs in os.environ
    return func.HttpResponse(f"Hello! DB: {db_host}")

For Library Developers

git clone https://github.com/TheViziusGroup/azure-bootstrap
cd azure-bootstrap
python -m venv .venv
.venv\Scripts\activate
pip install -e ".[dev]"
pytest

๐Ÿ“ฆ Installation

From PyPI

pip install azure-bootstrap

Add to requirements.txt:

azure-bootstrap>=1.0.0

โš™๏ธ Configuration

Option 1: Enterprise (Azure App Configuration + Key Vault)

local.settings.json:

{
  "Values": {
    "AZURE_APP_CONFIGURATION_CONNECTION_STRING": "Endpoint=https://...;Id=...;Secret=...",
    "AZURE_KEY_VAULT_URL": "https://myvault.vault.azure.net/",
    "AZURE_APP_CONFIG_LABEL": "dev"
  }
}

Option 2: Simple (Environment Variables Only)

local.settings.json:

{
  "Values": {
    "DATABASE_HOST": "localhost",
    "DATABASE_NAME": "mydb",
    "API_KEY": "your-api-key"
  }
}

The library gracefully falls back to environment variables when App Configuration is not available.

Configuration Precedence

Priority Order (highest to lowest):

  1. Environment variables (os.environ) - Local overrides win
  2. Azure App Configuration - Centralized config
  3. Key Vault secrets - Secure secrets (via App Config references)
  4. Default values - Fallback

Example:

# local.settings.json sets: USE_MOCK_DB = "true"
# App Config has: USE_MOCK_DB = "false"
# After bootstrap: os.getenv("USE_MOCK_DB") โ†’ "true" (local wins!)

๐Ÿ’ก Usage Examples

Complete Azure Functions Example

See examples/function_app_example.py for a production-ready example.

Basic Usage

from azure_bootstrap import initialize_application, get_bootstrap_logger

logger = get_bootstrap_logger(__name__)
config_repo = initialize_application()

# All configs now in os.environ
db_host = os.getenv("DATABASE_HOST")

Custom Secrets Repository

from azure_bootstrap import initialize_application, SecretsRepository

secrets_repo = SecretsRepository(vault_url="https://custom-vault.vault.azure.net/")
config_repo = initialize_application(secrets_repository=secrets_repo)

Without Auto-Loading to os.environ

from azure_bootstrap import create_enhanced_config_repository

config_repo = create_enhanced_config_repository(
    app_config_connection_string=conn_str,
    auto_load_to_environ=False
)

# Manually access values
db_host = config_repo.get_value("DATABASE_HOST")

๐Ÿ“– API Reference

Main Functions

initialize_application(secrets_repository=None)

Main bootstrap function that initializes the entire application.

Returns: EnhancedConfigRepository instance

Example:

config_repo = initialize_application()

get_bootstrap_logger(name)

Get a logger that works during bootstrap phase.

Parameters: name (str) - Logger name (typically __name__)

Returns: logging.Logger

Example:

logger = get_bootstrap_logger(__name__)

create_enhanced_config_repository(...)

Create a configuration repository with App Config and Key Vault support.

Parameters:

  • app_config_connection_string (str): Azure App Configuration connection string
  • secrets_repository (optional): Custom secrets repository
  • auto_load_to_environ (bool): Auto-load configs to os.environ

Returns: EnhancedConfigRepository

Core Classes

  • ApplicationBootstrap - Bootstrap orchestrator
  • EnhancedConfigRepository - Configuration repository
  • SecretsRepository - Key Vault secrets repository
  • TelemetryManager - Telemetry and App Insights manager
  • BootstrapLogger - Bootstrap logging manager

Interfaces

All components implement interfaces for testability:

  • ApplicationBootstrapInterface
  • EnhancedConfigRepositoryInterface
  • SecretsRepositoryInterface
  • TelemetryManagerInterface
  • BootstrapLoggerInterface

๐Ÿ”„ Migration Guide

Converting Projects from Local Bootstrap Code

Step 1: Backup and Branch

git checkout -b backup-before-bootstrap-migration
git push origin backup-before-bootstrap-migration
git checkout -b migrate-to-bootstrap-library

Step 2: Install and Update Imports

pip install azure-bootstrap
# BEFORE:
from src.infrastructure.application_bootstrap import initialize_application
from src.infrastructure.bootstrap_logging import get_bootstrap_logger

# AFTER:
from azure_bootstrap import initialize_application, get_bootstrap_logger

Find all files to update:

grep -r "from src.infrastructure" .
grep -r "from src.repositories.enhanced_config_repository" .
grep -r "from src.repositories.secrets_repository" .

Step 3: Remove Local Bootstrap Files

rm -rf src/infrastructure/
# Only remove these if you don't have app-specific extensions:
rm -f src/repositories/enhanced_config_repository.py
rm -f src/repositories/secrets_repository.py

Step 4: Update requirements.txt

azure-bootstrap>=1.0.0
# Remove: azure-appconfiguration-provider, azure-keyvault-secrets,
# azure-identity, azure-monitor-opentelemetry (now included in library)

Step 5: Update Deployment Pipeline

# In your CI/CD pipeline, just install from PyPI:
- script: pip install -r requirements.txt

Migration Scenarios

Scenario Complexity Time What to Do
Basic Function Easy 15 min Update imports, remove src/infrastructure/
Custom Config Repository Medium 30 min Keep your custom repo, inherit from EnhancedConfigRepository
Custom Bootstrap Logic Advanced 1 hour Keep custom bootstrap, use initialize_application() as foundation
Custom Telemetry Medium 30 min Use telemetry_manager.create_span() for custom spans

Post-Migration Checklist

  • Application starts without errors
  • Bootstrap logging works
  • App Configuration loads (if configured)
  • Key Vault secrets resolve (if configured)
  • App Insights telemetry works
  • All functions work as expected

Rollback Plan

# Revert migration
git revert <commit-hash>

# Or switch to backup branch
git checkout backup-before-bootstrap-migration

๐Ÿ› ๏ธ Development

Setup Development Environment

# Clone repository
git clone https://github.com/TheViziusGroup/azure-bootstrap
cd azure-bootstrap

# Create virtual environment
python -m venv .venv
.venv\Scripts\activate  # Windows
source .venv/bin/activate  # Linux/Mac

# Install with dev dependencies
pip install -e ".[dev]"

# Verify setup
pytest

Run Tests

# All tests with coverage
pytest --cov=azure_bootstrap --cov-report=term-missing

# Specific test
pytest test/services/test_application_bootstrap.py -v

# Generate HTML coverage report
pytest --cov=azure_bootstrap --cov-report=html
open htmlcov/index.html

Build Package

# Install build tools
pip install build twine

# Build wheel and source distribution
python -m build

# Output:
# dist/azure_bootstrap-1.0.0-py3-none-any.whl
# dist/azure_bootstrap-1.0.0.tar.gz

# Verify package
twine check dist/*

Publish to PyPI

# Manual publish
pip install twine
twine upload dist/*

# Or automated via pipeline
git tag v1.0.0
git push origin main --tags

๐Ÿ‘ฅ Contributing

We welcome contributions! Please follow these guidelines:

Git Workflow (Gitflow)

main (production)
โ””โ”€โ”€ dev (integration)
    โ”œโ”€โ”€ feature/feature-name
    โ”œโ”€โ”€ bugfix/bug-description
    โ””โ”€โ”€ hotfix/critical-fix

Branch Types

  • feature/* - New features (branch from dev, merge to dev)
  • bugfix/* - Bug fixes (branch from dev, merge to dev)
  • hotfix/* - Critical fixes (branch from main, merge to main AND dev)
  • release/* - Release preparation (branch from dev, merge to main and dev)

Quality Standards

  • โœ… Test Coverage: Minimum 80% (90% for new code)
  • โœ… Code Style: Black formatting, Ruff linting
  • โœ… Type Hints: Required for all public APIs
  • โœ… Documentation: Docstrings for all public functions
  • โœ… Commit Messages: Conventional Commits format

Pre-PR Checklist

# Format code
black azure_bootstrap/ test/

# Lint code
ruff check azure_bootstrap/ test/

# Type check
mypy azure_bootstrap/

# Run tests
pytest --cov=azure_bootstrap --cov-report=term-missing

# All checks must pass โœ…

See CONTRIBUTING.md for complete guidelines.


๐Ÿ”ง Troubleshooting

Common Issues

Issue: Module not found

# Solution
pip install azure-bootstrap

Issue: Import errors

# WRONG
from azure_bootstrap.infrastructure import initialize_application

# CORRECT
from azure_bootstrap import initialize_application

Issue: Tests failing

# Clean environment
rm -rf .venv
python -m venv .venv
.venv\Scripts\activate
pip install -e ".[test]"
pytest

Issue: Package not found on PyPI

# Verify the package is published
pip install azure-bootstrap --verbose

๐Ÿ“š Documentation

Core Documentation

Document Audience Purpose
README.md Everyone Complete library documentation (you are here)
CLAUDE.md AI Assistants & Developers Development context, version history, CI/CD setup
CONTRIBUTING.md Contributors Git workflow, quality standards, tooling setup, PR process
LICENSE Everyone License terms

Examples

File Purpose
examples/function_app_example.py Complete Azure Functions example
examples/local.settings.json.example Configuration examples

๐Ÿ“‹ Repository Structure

azure-bootstrap/
โ”œโ”€โ”€ azure_bootstrap/          # ๐Ÿ“ฆ Main package (17 .py files)
โ”‚   โ”œโ”€โ”€ models/                   # Exception definitions
โ”‚   โ”œโ”€โ”€ repositories/             # Config & secrets repositories
โ”‚   โ””โ”€โ”€ services/                 # Bootstrap services
โ”œโ”€โ”€ test/                         # ๐Ÿงช Test suite (80%+ coverage)
โ”œโ”€โ”€ examples/                     # ๐Ÿ’ก Usage examples
โ”œโ”€โ”€ .github/workflows/ci-cd.yml   # ๐Ÿ”„ GitHub Actions CI/CD
โ”œโ”€โ”€ .githooks/                    # ๐Ÿช Git hooks (pre-commit, pre-push)
โ”œโ”€โ”€ .vscode/                      # ๐Ÿ’ป VS Code workspace config
โ”œโ”€โ”€ pyproject.toml                # โš™๏ธ Package configuration
โ”œโ”€โ”€ README.md                     # ๐Ÿ‘ˆ You are here
โ”œโ”€โ”€ CLAUDE.md                     # ๐Ÿค– AI assistant context & version history
โ”œโ”€โ”€ CONTRIBUTING.md               # ๐Ÿ‘ฅ Contribution guidelines & tooling setup
โ””โ”€โ”€ LICENSE                       # ๐Ÿ“„ License file

๐Ÿงช Testing

Test Coverage

  • Current: 82% overall coverage (82.43%)
  • Requirement: 80% minimum, 90% for new code
  • Critical Paths: 100% coverage (bootstrap flow, config loading)

Run Tests

pytest                           # All tests
pytest -v                        # Verbose
pytest --cov                     # With coverage
pytest test/services/ -v         # Specific directory

๐Ÿ“ฆ Package Distribution

What Gets Distributed

โœ… Package code (17 .py files) โœ… Type hints (py.typed) โœ… LICENSE file

What Doesn't Get Distributed

โŒ Tests (test/) โŒ Examples (examples/) โŒ Development files (.gitignore, etc.) โŒ Build artifacts (dist/, build/)

See MANIFEST.in for distribution control.


๐Ÿ”„ CI/CD Pipeline

GitHub Actions Workflow

The library uses GitHub Actions for continuous integration and deployment. The workflow automatically:

  1. Build & Test - Installs dependencies, runs tests with coverage
  2. Publish - Uploads package to PyPI (main branch and tags only)
  3. Validate - Tests installation from feed

Triggers

  • Push to main โ†’ Stable release (e.g., 1.0.0)
  • Push to develop โ†’ Development release with timestamp (e.g., 1.0.0.dev20250124123456)
  • Pull requests โ†’ Build and test only (no publish)
  • Tags (v)* โ†’ Tagged stable release

See .github/workflows/ci-cd.yml for workflow configuration.

For complete CI/CD setup instructions, see the CI/CD Setup section in CLAUDE.md.


๐Ÿ“ Version Management

Semantic Versioning

  • Major (X.0.0) - Breaking API changes
  • Minor (0.X.0) - New features (backwards compatible)
  • Patch (0.0.X) - Bug fixes

Current Version: 1.0.0

See the Version History section in CLAUDE.md for detailed changelog.


๐ŸŽฏ Used By

This library is used across 17+ repositories:

  • AI Assistant + Vector Store Manager
  • Excel Operations Processor
  • Email Ingestion Service
  • HITL Review Service
  • ... (13 more Azure Functions projects)

๐Ÿ“‹ Requirements

Runtime Requirements

  • Python 3.11+
  • Azure subscription with:
    • Azure App Configuration (optional)
    • Azure Key Vault (optional)
    • Application Insights (optional)

Dependencies

azure-appconfiguration-provider >= 1.0.0
azure-keyvault-secrets >= 4.7.0
azure-identity >= 1.15.0
azure-monitor-opentelemetry >= 1.2.0
opentelemetry-api >= 1.22.0
opentelemetry-instrumentation-azure-functions >= 0.45b0

โญ Key Benefits

For the Organization

  • โœ… Single Source of Truth - One codebase for 17+ projects
  • โœ… Consistent Behavior - Same bootstrap logic everywhere
  • โœ… Easy Maintenance - Fix bugs once, benefit everywhere
  • โœ… Version Control - Semantic versioning with changelogs

For Developers

  • โœ… Simple Integration - Just pip install and 2-line import
  • โœ… No Implementation Knowledge - Use public API, done
  • โœ… Type-Safe - Full type hints for IDE support
  • โœ… Well-Tested - 80%+ coverage, production-proven

For Operations

  • โœ… Centralized Updates - Deploy improvements once
  • โœ… Reduced Duplication - No copy-paste errors
  • โœ… Better Monitoring - Consistent telemetry
  • โœ… Easier Debugging - Same code across projects

๐Ÿ“„ License

MIT License - See LICENSE for details.


๐Ÿ†˜ Support


Ready to get started? Install the library and see examples/function_app_example.py for a complete working example!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure_bootstrap-1.0.0.tar.gz (34.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

azure_bootstrap-1.0.0-py3-none-any.whl (35.6 kB view details)

Uploaded Python 3

File details

Details for the file azure_bootstrap-1.0.0.tar.gz.

File metadata

  • Download URL: azure_bootstrap-1.0.0.tar.gz
  • Upload date:
  • Size: 34.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for azure_bootstrap-1.0.0.tar.gz
Algorithm Hash digest
SHA256 51f41abb2a1e576b51c466f72c692fb3d4a8d4d80bff782200d212ba3b28b887
MD5 ce58381ead3ca36e2e25e81bedae6e9b
BLAKE2b-256 ce4413d2dbfb74331c5fea3fabfa764f5438be8a27c353b910d83b9cd3df3ed6

See more details on using hashes here.

Provenance

The following attestation bundles were made for azure_bootstrap-1.0.0.tar.gz:

Publisher: ci-cd.yml on TheViziusGroup/azure-bootstrap

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file azure_bootstrap-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_bootstrap-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a2d9cb84f84976619eea417eeda021df9ef861011f13876d9f00bbfa05d53544
MD5 d97288c89d513b1d1a744c8b14f30580
BLAKE2b-256 155cb312cc24db9a11a5d4bcf42da75482384a801238ec3ecc19a6b6b05243fa

See more details on using hashes here.

Provenance

The following attestation bundles were made for azure_bootstrap-1.0.0-py3-none-any.whl:

Publisher: ci-cd.yml on TheViziusGroup/azure-bootstrap

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page