CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-mgmt-appconfiguration

Microsoft Azure App Configuration Management Client Library for Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

snapshots.mddocs/

Snapshot Operations

The SnapshotsOperations class provides management capabilities for Azure App Configuration snapshots. Snapshots capture the state of configuration data at a specific point in time, enabling versioning, backup, and rollback scenarios for your configuration management.

Operations Class

class SnapshotsOperations:
    """
    Operations for managing App Configuration snapshots.
    
    Snapshots provide point-in-time captures of configuration data, allowing you to:
    - Create versioned backups of configuration state
    - Enable rollback to previous configurations
    - Capture configuration for specific releases or deployments
    - Audit configuration changes over time
    """

Snapshot Management

Get Snapshot

def get(
    self, 
    resource_group_name: str, 
    config_store_name: str, 
    snapshot_name: str, 
    **kwargs: Any
) -> Snapshot:
    """
    Gets the properties and status of a configuration snapshot.
    
    Args:
        resource_group_name: The name of the resource group containing the store.
        config_store_name: The name of the configuration store.
        snapshot_name: The name of the snapshot.
        **kwargs: Additional keyword arguments for the request.
        
    Returns:
        Snapshot: The snapshot details including status, composition type, and filters.
        
    Example:
        >>> snapshot = client.snapshots.get("my-rg", "my-store", "release-v1.0")
        >>> print(f"Snapshot status: {snapshot.status}")
        >>> print(f"Items count: {snapshot.items_count}")
        >>> print(f"Size: {snapshot.size_in_bytes} bytes")
        >>> print(f"Created: {snapshot.created}")
    """

Create Snapshot

def begin_create(
    self, 
    resource_group_name: str, 
    config_store_name: str, 
    snapshot_name: str, 
    snapshot_creation_parameters: Snapshot, 
    **kwargs: Any
) -> LROPoller[Snapshot]:
    """
    Creates a new configuration snapshot with the specified parameters.
    
    Args:
        resource_group_name: The name of the resource group containing the store.
        config_store_name: The name of the configuration store.
        snapshot_name: The name for the snapshot (must be unique within the store).
        snapshot_creation_parameters: Parameters defining what to include in the snapshot.
        **kwargs: Additional keyword arguments for the request.
        
    Returns:
        LROPoller[Snapshot]: A poller for the long-running create operation.
        
    Note:
        Snapshot creation is asynchronous. The snapshot status will be "Provisioning" 
        during creation and "Ready" when complete. Large configuration sets may take 
        several minutes to snapshot.
        
    Example:
        >>> from azure.mgmt.appconfiguration.models import (
        ...     Snapshot, KeyValueFilter, CompositionType
        ... )
        >>> # Create snapshot of all production configs
        >>> filters = [KeyValueFilter(key="MyApp:*", label="Production")]
        >>> snapshot_params = Snapshot(
        ...     filters=filters,
        ...     composition_type=CompositionType.KEY_LABEL,
        ...     retention_period=7776000  # 90 days in seconds
        ... )
        >>> create_poller = client.snapshots.begin_create(
        ...     "my-rg", "my-store", "prod-release-v2.1", snapshot_params
        ... )
        >>> snapshot = create_poller.result()  # Wait for completion
    """

Snapshot Model

Snapshot Class

class Snapshot:
    """
    Represents a configuration snapshot in Azure App Configuration.
    
    Attributes:
        id (str): The resource ID of the snapshot (read-only).
        name (str): The name of the snapshot (read-only).
        type (str): The resource type (read-only).
        filters (List[KeyValueFilter]): Filters that determine which key-values are included.
        composition_type (CompositionType): How the snapshot composes key-value pairs.
        retention_period (int): Retention period in seconds (1-7776000, max 90 days).
        status (SnapshotStatus): Current status of the snapshot (read-only).
        provisioning_state (str): ARM provisioning state (read-only).
        created (datetime): When the snapshot was created (read-only).
        expires (datetime): When the snapshot expires (read-only).
        size_in_bytes (int): Size of the snapshot in bytes (read-only).
        items_count (int): Number of key-value pairs in the snapshot (read-only).
        tags (Dict[str, str]): Tags associated with the snapshot.
        etag (str): The ETag for concurrency control (read-only).
    """
    
    def __init__(
        self,
        *,
        filters: List[KeyValueFilter],
        composition_type: CompositionType,
        retention_period: Optional[int] = None,
        tags: Optional[Dict[str, str]] = None,
        **kwargs: Any
    ) -> None:
        """
        Initialize a Snapshot instance.
        
        Args:
            filters: List of filters to determine which key-values to include.
            composition_type: How to compose key-value pairs (KEY or KEY_LABEL).
            retention_period: Retention period in seconds (default: 2592000 = 30 days).
            tags: Tags to associate with the snapshot.
        """

KeyValueFilter Class

class KeyValueFilter:
    """
    Filter criteria for including key-value pairs in snapshots.
    
    Attributes:
        key (str): Key pattern to match (supports wildcards like "MyApp:*").
        label (str): Label to match (optional, empty string matches unlabeled keys).
    """
    
    def __init__(
        self,
        *,
        key: str,
        label: Optional[str] = None,
        **kwargs: Any
    ) -> None:
        """
        Initialize a KeyValueFilter.
        
        Args:
            key: Key pattern to match (use "*" for wildcards).
            label: Label to match (None or empty string matches unlabeled keys).
        """

CompositionType Enumeration

class CompositionType:
    """
    Enumeration of snapshot composition types.
    
    Values:
        KEY: Snapshot composes key-value pairs by key only (ignores labels).
        KEY_LABEL: Snapshot composes key-value pairs by both key and label.
    """
    KEY = "Key"
    KEY_LABEL = "Key_Label"

SnapshotStatus Enumeration

class SnapshotStatus:
    """
    Enumeration of snapshot status values.
    
    Values:
        PROVISIONING: Snapshot is being created.
        READY: Snapshot has been created successfully and is available.
        ARCHIVED: Snapshot has been archived (past retention period).
        FAILED: Snapshot creation has failed.
    """
    PROVISIONING = "Provisioning"
    READY = "Ready"
    ARCHIVED = "Archived"
    FAILED = "Failed"

Practical Usage Examples

Basic Snapshot Creation

from azure.mgmt.appconfiguration import AppConfigurationManagementClient
from azure.mgmt.appconfiguration.models import (
    Snapshot,
    KeyValueFilter, 
    CompositionType,
    SnapshotStatus
)
from azure.identity import DefaultAzureCredential
import datetime

# Initialize client
credential = DefaultAzureCredential()
client = AppConfigurationManagementClient(credential, "subscription-id")

resource_group = "my-resource-group"
store_name = "my-config-store"

# Create a simple snapshot of all configuration
print("Creating snapshot of all configuration...")

# Define filters - capture all keys
all_config_filter = KeyValueFilter(key="*")  # All keys

snapshot_params = Snapshot(
    filters=[all_config_filter],
    composition_type=CompositionType.KEY_LABEL,  # Include labels
    retention_period=2592000,  # 30 days
    tags={
        "Purpose": "Full Backup",
        "Created": datetime.datetime.now().isoformat(),
        "Version": "1.0"
    }
)

# Create the snapshot
create_poller = client.snapshots.begin_create(
    resource_group,
    store_name,
    "full-backup-snapshot",
    snapshot_params
)

print("Snapshot creation started...")
snapshot = create_poller.result()  # Wait for completion

print(f"Snapshot created successfully!")
print(f"Name: {snapshot.name}")
print(f"Status: {snapshot.status}")
print(f"Items: {snapshot.items_count}")
print(f"Size: {snapshot.size_in_bytes} bytes")
print(f"Expires: {snapshot.expires}")

Application Release Snapshots

def create_release_snapshots():
    """Create snapshots for different application releases."""
    
    # Define release configurations
    releases = {
        "v1.0": {
            "filters": [
                KeyValueFilter(key="MyApp:*", label="Production"),
                KeyValueFilter(key="Shared:*", label="Production")
            ],
            "description": "Production configuration for v1.0 release"
        },
        "v1.1-beta": {
            "filters": [
                KeyValueFilter(key="MyApp:*", label="Beta"),
                KeyValueFilter(key="Shared:*", label="Beta"),
                KeyValueFilter(key="Features:*", label="Beta")
            ],
            "description": "Beta configuration for v1.1 release"
        },
        "v2.0-preview": {
            "filters": [
                KeyValueFilter(key="MyApp:v2:*", label="Preview"),
                KeyValueFilter(key="NewFeatures:*", label="Preview")
            ],
            "description": "Preview configuration for v2.0 release"
        }
    }
    
    print("=== Creating Release Snapshots ===")
    
    created_snapshots = {}
    
    for version, config in releases.items():
        snapshot_name = f"release-{version}"
        
        print(f"\nCreating snapshot for {version}...")
        print(f"Description: {config['description']}")
        
        # Create snapshot with version-specific filters
        snapshot_params = Snapshot(
            filters=config["filters"],
            composition_type=CompositionType.KEY_LABEL,
            retention_period=7776000,  # 90 days for release snapshots
            tags={
                "Release": version,
                "Type": "Release",
                "Description": config["description"],
                "Created": datetime.datetime.now().isoformat()
            }
        )
        
        try:
            create_poller = client.snapshots.begin_create(
                resource_group,
                store_name,
                snapshot_name,
                snapshot_params
            )
            
            print(f"  ⏳ Creating snapshot...")
            snapshot = create_poller.result()
            
            created_snapshots[version] = snapshot
            
            print(f"  ✅ Snapshot created for {version}")
            print(f"     Items: {snapshot.items_count}")
            print(f"     Size: {snapshot.size_in_bytes} bytes")
            print(f"     Expires: {snapshot.expires}")
            
        except Exception as e:
            print(f"  ❌ Failed to create snapshot for {version}: {e}")
            created_snapshots[version] = None
    
    # Summary
    successful_snapshots = [v for v, s in created_snapshots.items() if s is not None]
    print(f"\n=== Summary ===")
    print(f"Successfully created {len(successful_snapshots)} release snapshots:")
    
    for version in successful_snapshots:
        snapshot = created_snapshots[version]
        print(f"  - {version}: {snapshot.name} ({snapshot.items_count} items)")
    
    return created_snapshots

# Create release snapshots
release_snapshots = create_release_snapshots()

Environment-Specific Snapshots

def create_environment_snapshots():
    """Create snapshots for different environments."""
    
    environments = ["Development", "Staging", "Production"]
    
    print("=== Creating Environment Snapshots ===")
    
    env_snapshots = {}
    
    for env in environments:
        print(f"\nProcessing {env} environment...")
        
        # Create environment-specific filters
        env_filters = [
            KeyValueFilter(key="*", label=env),  # All keys with env label
            KeyValueFilter(key=f"{env}:*")       # Keys specific to environment
        ]
        
        # Adjust retention based on environment
        retention_days = {
            "Development": 7,    # 7 days
            "Staging": 30,       # 30 days  
            "Production": 90     # 90 days
        }
        
        retention_seconds = retention_days[env] * 24 * 60 * 60
        
        snapshot_params = Snapshot(
            filters=env_filters,
            composition_type=CompositionType.KEY_LABEL,
            retention_period=retention_seconds,
            tags={
                "Environment": env,
                "Type": "Environment Backup",
                "Retention": f"{retention_days[env]} days",
                "Created": datetime.datetime.now().isoformat()
            }
        )
        
        snapshot_name = f"env-{env.lower()}-{datetime.datetime.now().strftime('%Y%m%d')}"
        
        try:
            create_poller = client.snapshots.begin_create(
                resource_group,
                store_name, 
                snapshot_name,
                snapshot_params
            )
            
            snapshot = create_poller.result()
            env_snapshots[env] = snapshot
            
            print(f"  ✅ {env} snapshot created: {snapshot.name}")
            print(f"     Items: {snapshot.items_count}")
            print(f"     Retention: {retention_days[env]} days")
            
        except Exception as e:
            print(f"  ❌ Failed to create {env} snapshot: {e}")
            env_snapshots[env] = None
    
    return env_snapshots

# Create environment snapshots
env_snapshots = create_environment_snapshots()

Feature Flag Snapshots

def create_feature_flag_snapshots():
    """Create snapshots specifically for feature flags."""
    
    print("=== Creating Feature Flag Snapshots ===")
    
    # Feature flag specific filters
    feature_flag_filters = [
        KeyValueFilter(key=".appconfig.featureflag/*"),  # All feature flags
        KeyValueFilter(key="FeatureManagement:*")        # Alternative feature flag pattern
    ]
    
    # Create snapshot for current feature flag state
    timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M")
    snapshot_name = f"feature-flags-{timestamp}"
    
    snapshot_params = Snapshot(
        filters=feature_flag_filters,
        composition_type=CompositionType.KEY_LABEL,
        retention_period=1209600,  # 14 days for feature flags
        tags={
            "Type": "Feature Flags",
            "Purpose": "Feature Flag State Backup", 
            "Timestamp": timestamp
        }
    )
    
    print(f"Creating feature flag snapshot: {snapshot_name}")
    
    try:
        create_poller = client.snapshots.begin_create(
            resource_group,
            store_name,
            snapshot_name,
            snapshot_params
        )
        
        snapshot = create_poller.result()
        
        print(f"✅ Feature flag snapshot created:")
        print(f"   Name: {snapshot.name}")
        print(f"   Items: {snapshot.items_count}")
        print(f"   Size: {snapshot.size_in_bytes} bytes")
        
        # Analyze feature flag snapshot content
        if snapshot.items_count > 0:
            print(f"   📊 Analysis:")
            print(f"   - Captured {snapshot.items_count} feature flag configurations")
            print(f"   - Snapshot size: {snapshot.size_in_bytes:,} bytes")
            print(f"   - Average bytes per flag: {snapshot.size_in_bytes // snapshot.items_count:.0f}")
        
        return snapshot
        
    except Exception as e:
        print(f"❌ Failed to create feature flag snapshot: {e}")
        return None

# Create feature flag snapshot
ff_snapshot = create_feature_flag_snapshots()

Snapshot Monitoring and Management

def monitor_snapshot_status():
    """Monitor the status of existing snapshots."""
    
    print("=== Snapshot Status Monitor ===")
    
    # Note: There's no list operation in the ARM API for snapshots
    # In practice, you would track snapshot names separately
    # This example shows how to check status of known snapshots
    
    known_snapshots = [
        "full-backup-snapshot",
        "release-v1.0", 
        "release-v1.1-beta",
        "env-production-20241201",
        "feature-flags-20241201-1400"
    ]
    
    snapshot_status = {}
    
    for snapshot_name in known_snapshots:
        try:
            snapshot = client.snapshots.get(resource_group, store_name, snapshot_name)
            
            snapshot_status[snapshot_name] = {
                "status": snapshot.status,
                "created": snapshot.created,
                "expires": snapshot.expires,
                "items_count": snapshot.items_count,
                "size_in_bytes": snapshot.size_in_bytes,
                "tags": snapshot.tags
            }
            
            print(f"\n📸 Snapshot: {snapshot_name}")
            print(f"   Status: {snapshot.status}")
            print(f"   Created: {snapshot.created}")
            print(f"   Expires: {snapshot.expires}")
            print(f"   Items: {snapshot.items_count}")
            print(f"   Size: {snapshot.size_in_bytes:,} bytes")
            
            # Check expiration warning
            if snapshot.expires:
                days_until_expiry = (snapshot.expires - datetime.datetime.now(datetime.timezone.utc)).days
                if days_until_expiry <= 7:
                    print(f"   ⚠️  Expires in {days_until_expiry} days!")
                elif days_until_expiry <= 1:
                    print(f"   🚨 Expires in {days_until_expiry} day(s)!")
            
            # Status-specific messages
            if snapshot.status == SnapshotStatus.PROVISIONING:
                print(f"   ⏳ Still being created...")
            elif snapshot.status == SnapshotStatus.READY:
                print(f"   ✅ Ready for use")
            elif snapshot.status == SnapshotStatus.ARCHIVED:
                print(f"   📦 Archived (past retention period)")
            elif snapshot.status == SnapshotStatus.FAILED:
                print(f"   ❌ Creation failed")
            
        except Exception as e:
            print(f"\n❌ Error checking {snapshot_name}: {e}")
            snapshot_status[snapshot_name] = {"error": str(e)}
    
    # Summary statistics
    print(f"\n=== Summary ===")
    
    status_counts = {}
    total_items = 0
    total_size = 0
    
    for name, info in snapshot_status.items():
        if "error" not in info:
            status = info["status"]
            status_counts[status] = status_counts.get(status, 0) + 1
            total_items += info["items_count"]
            total_size += info["size_in_bytes"]
    
    print(f"Total snapshots checked: {len(known_snapshots)}")
    for status, count in status_counts.items():
        print(f"  {status}: {count}")
    
    if total_items > 0:
        print(f"Total configuration items: {total_items:,}")
        print(f"Total storage used: {total_size:,} bytes ({total_size/1024/1024:.2f} MB)")
    
    return snapshot_status

# Monitor snapshots
snapshot_monitoring = monitor_snapshot_status()

Snapshot Comparison and Analysis

def analyze_snapshot_differences():
    """Analyze differences between snapshots for change tracking."""
    
    print("=== Snapshot Analysis ===")
    
    # Compare two snapshots (in practice, you might have utilities to extract and compare)
    snapshots_to_compare = ["release-v1.0", "release-v1.1-beta"]
    
    snapshot_data = {}
    
    for snapshot_name in snapshots_to_compare:
        try:
            snapshot = client.snapshots.get(resource_group, store_name, snapshot_name)
            snapshot_data[snapshot_name] = snapshot
            
            print(f"\n📊 Snapshot: {snapshot_name}")
            print(f"   Created: {snapshot.created}")
            print(f"   Status: {snapshot.status}")
            print(f"   Items: {snapshot.items_count}")
            print(f"   Size: {snapshot.size_in_bytes:,} bytes")
            
            if snapshot.tags:
                print(f"   Tags:")
                for key, value in snapshot.tags.items():
                    print(f"     {key}: {value}")
        
        except Exception as e:
            print(f"❌ Error loading {snapshot_name}: {e}")
    
    # Basic comparison (metadata only via ARM API)
    if len(snapshot_data) == 2:
        snap1_name, snap2_name = snapshots_to_compare
        snap1 = snapshot_data.get(snap1_name)
        snap2 = snapshot_data.get(snap2_name)
        
        if snap1 and snap2:
            print(f"\n🔍 Comparison: {snap1_name} vs {snap2_name}")
            
            item_diff = snap2.items_count - snap1.items_count
            size_diff = snap2.size_in_bytes - snap1.size_in_bytes
            
            print(f"   Item count change: {item_diff:+d}")
            print(f"   Size change: {size_diff:+,} bytes")
            
            if item_diff > 0:
                print(f"   📈 {item_diff} new configuration items added")
            elif item_diff < 0:
                print(f"   📉 {abs(item_diff)} configuration items removed")
            else:
                print(f"   ➡️  Same number of items (possible updates)")
            
            # Time analysis
            if snap1.created and snap2.created:
                time_diff = snap2.created - snap1.created
                print(f"   Time between snapshots: {time_diff}")
    
    # Recommendations based on analysis
    print(f"\n💡 Recommendations:")
    
    ready_snapshots = [name for name, data in snapshot_data.items() 
                      if data and data.status == SnapshotStatus.READY]
    
    if len(ready_snapshots) >= 2:
        print(f"   - Use data plane API to compare actual configuration content")
        print(f"   - Consider automated snapshot comparison for CI/CD pipelines")
        print(f"   - Set up alerts for significant configuration changes")
    
    return snapshot_data

# Analyze snapshots
snapshot_analysis = analyze_snapshot_differences()

Snapshot Lifecycle Management

def manage_snapshot_lifecycle():
    """Implement a comprehensive snapshot lifecycle management strategy."""
    
    print("=== Snapshot Lifecycle Management ===")
    
    # Define lifecycle policies
    policies = {
        "daily_backup": {
            "schedule": "daily",
            "retention_days": 7,
            "filters": [KeyValueFilter(key="*")],  # All config
            "name_pattern": "daily-backup-{date}"
        },
        "weekly_backup": {
            "schedule": "weekly", 
            "retention_days": 30,
            "filters": [KeyValueFilter(key="*")],
            "name_pattern": "weekly-backup-{date}"
        },
        "release_snapshot": {
            "schedule": "on_demand",
            "retention_days": 90,
            "filters": [KeyValueFilter(key="*", label="Production")],
            "name_pattern": "release-{version}"
        },
        "feature_flags": {
            "schedule": "twice_daily",
            "retention_days": 14,
            "filters": [KeyValueFilter(key=".appconfig.featureflag/*")],
            "name_pattern": "ff-{datetime}"
        }
    }
    
    current_date = datetime.datetime.now()
    
    # Simulate creating snapshots based on policies
    for policy_name, policy in policies.items():
        print(f"\n📋 Policy: {policy_name}")
        print(f"   Schedule: {policy['schedule']}")
        print(f"   Retention: {policy['retention_days']} days")
        
        # Generate snapshot name based on pattern
        if "{date}" in policy["name_pattern"]:
            snapshot_name = policy["name_pattern"].replace("{date}", current_date.strftime("%Y%m%d"))
        elif "{datetime}" in policy["name_pattern"]:
            snapshot_name = policy["name_pattern"].replace("{datetime}", current_date.strftime("%Y%m%d-%H%M"))
        else:
            snapshot_name = policy["name_pattern"]
        
        print(f"   Snapshot name: {snapshot_name}")
        
        # Create snapshot based on policy
        retention_seconds = policy["retention_days"] * 24 * 60 * 60
        
        snapshot_params = Snapshot(
            filters=policy["filters"],
            composition_type=CompositionType.KEY_LABEL,
            retention_period=retention_seconds,
            tags={
                "Policy": policy_name,
                "Schedule": policy["schedule"],
                "AutoCreated": "True",
                "Created": current_date.isoformat()
            }
        )
        
        # In a real implementation, you would check if it's time to create the snapshot
        # based on the schedule. For this example, we'll just show the process.
        print(f"   ✅ Would create snapshot with {len(policy['filters'])} filter(s)")
    
    # Cleanup old snapshots (simulation)
    print(f"\n🧹 Cleanup Process:")
    print(f"   - Check snapshots past retention period")
    print(f"   - Archive or delete expired snapshots") 
    print(f"   - Notify administrators of cleanup actions")
    
    # Best practices summary
    print(f"\n📚 Best Practices:")
    print(f"   - Automate snapshot creation based on business needs")
    print(f"   - Balance retention periods with storage costs")
    print(f"   - Use descriptive naming conventions")
    print(f"   - Tag snapshots for easy identification and management")
    print(f"   - Monitor snapshot creation success/failure")
    print(f"   - Document snapshot and restore procedures")

# Run lifecycle management
manage_snapshot_lifecycle()

Asynchronous Operations

from azure.mgmt.appconfiguration.aio import AppConfigurationManagementClient
from azure.identity.aio import DefaultAzureCredential
import asyncio

async def async_snapshot_operations():
    """Demonstrate asynchronous snapshot operations."""
    
    credential = DefaultAzureCredential()
    
    async with AppConfigurationManagementClient(credential, "subscription-id") as client:
        
        # Create multiple snapshots concurrently
        snapshot_configs = [
            {
                "name": "async-full-backup",
                "filters": [KeyValueFilter(key="*")],
                "tags": {"Type": "Full Backup", "Async": "True"}
            },
            {
                "name": "async-app-config", 
                "filters": [KeyValueFilter(key="MyApp:*")],
                "tags": {"Type": "App Config", "Async": "True"}
            },
            {
                "name": "async-feature-flags",
                "filters": [KeyValueFilter(key=".appconfig.featureflag/*")],
                "tags": {"Type": "Feature Flags", "Async": "True"}
            }
        ]
        
        print("Creating snapshots concurrently...")
        
        # Start all snapshot creations
        create_tasks = []
        for config in snapshot_configs:
            snapshot_params = Snapshot(
                filters=config["filters"],
                composition_type=CompositionType.KEY_LABEL,
                retention_period=2592000,  # 30 days
                tags=config["tags"]
            )
            
            task = client.snapshots.begin_create(
                resource_group,
                store_name,
                config["name"],
                snapshot_params
            )
            create_tasks.append((config["name"], task))
        
        # Wait for all create operations to start
        pollers = []
        for name, task in create_tasks:
            try:
                poller = await task
                pollers.append((name, poller))
                print(f"✓ Started creation of {name}")
            except Exception as e:
                print(f"✗ Failed to start {name}: {e}")
        
        # Wait for all snapshots to complete
        print("Waiting for snapshot creation to complete...")
        
        results = []
        for name, poller in pollers:
            try:
                snapshot = await poller.result()
                results.append(snapshot)
                print(f"✅ {name}: {snapshot.items_count} items, {snapshot.size_in_bytes} bytes")
            except Exception as e:
                print(f"❌ {name} failed: {e}")
        
        print(f"\nCompleted {len(results)} snapshots successfully")

# Run async operations
asyncio.run(async_snapshot_operations())

Integration with CI/CD Pipelines

def integrate_with_cicd():
    """Show how to integrate snapshots with CI/CD pipelines."""
    
    print("=== CI/CD Pipeline Integration ===")
    
    pipeline_examples = {
        "pre_deployment": {
            "trigger": "Before deployment",
            "purpose": "Backup current state before changes",
            "script": """
# Pre-deployment snapshot
az appconfig snapshot create \\
  --name "pre-deploy-$(Build.BuildNumber)" \\
  --config-store-name {store_name} \\
  --filters "key=*&label=Production" \\
  --retention-period 604800  # 7 days
"""
        },
        "post_deployment": {
            "trigger": "After successful deployment",
            "purpose": "Capture new configuration state",
            "script": """
# Post-deployment snapshot
az appconfig snapshot create \\
  --name "post-deploy-$(Build.BuildNumber)" \\
  --config-store-name {store_name} \\
  --filters "key=*&label=Production" \\
  --retention-period 2592000  # 30 days
"""
        },
        "rollback": {
            "trigger": "On deployment failure",
            "purpose": "Reference point for rollback procedures",
            "script": """
# Get latest pre-deployment snapshot
SNAPSHOT_NAME=$(az appconfig snapshot list \\
  --config-store-name {store_name} \\
  --query "[?contains(name, 'pre-deploy')].name | [-1]" -o tsv)

# Use snapshot as rollback reference
echo "Rollback to snapshot: $SNAPSHOT_NAME"
"""
        }
    }
    
    for stage, config in pipeline_examples.items():
        print(f"\n🔄 {stage.replace('_', ' ').title()}:")
        print(f"   Trigger: {config['trigger']}")
        print(f"   Purpose: {config['purpose']}")
        print(f"   Script:")
        print(f"{config['script']}")
    
    # Python SDK equivalent for CI/CD
    print(f"\n🐍 Python SDK Example for CI/CD:")
    print("""
import os
from azure.mgmt.appconfiguration import AppConfigurationManagementClient
from azure.mgmt.appconfiguration.models import Snapshot, KeyValueFilter, CompositionType
from azure.identity import DefaultAzureCredential

def create_deployment_snapshot(build_number: str, stage: str):
    client = AppConfigurationManagementClient(
        DefaultAzureCredential(), 
        os.environ["AZURE_SUBSCRIPTION_ID"]
    )
    
    snapshot_name = f"{stage}-{build_number}"
    filters = [KeyValueFilter(key="*", label="Production")]
    
    snapshot_params = Snapshot(
        filters=filters,
        composition_type=CompositionType.KEY_LABEL,
        retention_period=2592000,  # 30 days
        tags={
            "BuildNumber": build_number,
            "Stage": stage,
            "Pipeline": "CI/CD"
        }
    )
    
    poller = client.snapshots.begin_create(
        os.environ["RESOURCE_GROUP"],
        os.environ["CONFIG_STORE_NAME"],
        snapshot_name,
        snapshot_params
    )
    
    return poller.result()

# Usage in pipeline
if __name__ == "__main__":
    build_num = os.environ.get("BUILD_BUILDNUMBER", "manual")
    stage = os.environ.get("PIPELINE_STAGE", "pre-deploy")
    
    snapshot = create_deployment_snapshot(build_num, stage)
    print(f"Created snapshot: {snapshot.name}")
""")

integrate_with_cicd()

Install with Tessl CLI

npx tessl i tessl/pypi-azure-mgmt-appconfiguration

docs

configuration-stores.md

index.md

key-values.md

models-and-types.md

operations.md

private-networking.md

replicas.md

snapshots.md

tile.json