CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-molecule

Molecule aids in the development and testing of Ansible roles

Pending
Overview
Eval results
Files

configuration.mddocs/

Configuration

Molecule's configuration system provides type-safe management of scenarios, platforms, and testing parameters through a comprehensive set of configuration classes and data structures.

Capabilities

Core Configuration Class

Main configuration management class that orchestrates all aspects of a Molecule scenario.

class Config:
    """
    Main configuration management class.
    
    Instantiates and manages Driver, Platforms, Provisioner, Verifier,
    Scenario, and State references for a complete test environment.
    """
    
    def __init__(self, args=None, command_args=None):
        """
        Initialize configuration.
        
        Args:
            args (MoleculeArgs): Base Molecule arguments
            command_args (CommandArgs): Command-specific arguments
        """
    
    @property
    def driver(self):
        """Driver instance for infrastructure management."""
    
    @property
    def platforms(self):
        """Platforms configuration for test instances."""
    
    @property
    def provisioner(self): 
        """Provisioner for applying Ansible roles."""
    
    @property
    def verifier(self):
        """Verifier for running test suites."""
    
    @property
    def scenario(self):
        """Scenario configuration and state."""
    
    @property
    def state(self):
        """State management for tracking test progress."""

Configuration Data Types

Type-safe data structures for all aspects of Molecule configuration.

class ConfigData:
    """Class representing molecule config."""
    dependency: DependencyData
    driver: DriverData
    executor: ExecutorData
    platforms: list[PlatformData]
    prerun: bool
    role_name_check: int
    provisioner: ProvisionerData
    scenario: ScenarioData
    verifier: VerifierData

class ScenarioData:
    """Molecule scenario configuration."""
    name: str
    check_sequence: list[str]
    cleanup_sequence: list[str]
    converge_sequence: list[str]
    create_sequence: list[str]
    destroy_sequence: list[str]
    test_sequence: list[str]

class PlatformData:
    """Platform data for a Molecule run."""
    name: str
    groups: list[str]
    children: list[str]

class DependencyData:
    """Molecule dependency configuration."""
    name: str
    command: str | None
    enabled: bool
    options: dict[str, str | bool]
    env: dict[str, str]

class ProvisionerData:
    """Molecule provisioner configuration."""
    name: str
    config_options: dict[str, Any]
    ansible_args: list[str]
    connection_options: dict[str, Any]
    options: dict[str, str | bool]
    env: dict[str, str]
    inventory: InventoryData
    children: dict[str, Any]
    playbooks: PlaybookData
    log: bool

class PlaybookData:
    """Playbooks for a scenario."""
    cleanup: str
    create: str
    converge: str
    destroy: str
    prepare: str
    side_effect: str
    verify: str

class InventoryData:
    """Inventory data for a molecule run."""
    hosts: dict[str, str] 
    host_vars: dict[str, str]
    group_vars: dict[str, str]
    links: dict[str, str]

class ExecutorData:
    """Molecule playbook executor configuration."""
    backend: str

Command Arguments

Type definitions for command-line arguments and molecule execution parameters.

class MoleculeArgs:
    """Base arguments passed to all Molecule commands."""
    base_config: list[str]
    debug: bool
    env_file: str
    verbose: int

class CommandArgs:
    """Commandline arguments passed to molecule."""
    destroy: Literal["always", "never"]
    driver_name: str
    force: bool
    format: Literal["simple", "plain", "yaml"]
    host: str
    parallel: bool
    platform_name: str
    report: bool
    scenario_name: str
    shared_inventory: bool
    shared_state: bool
    subcommand: str

Status and Results

Data structures for tracking test execution status and results.

class Status:
    """NamedTuple with scenario status information."""
    instance_name: str
    driver_name: str
    provisioner_name: str
    scenario_name: str
    created: str  # String representation of boolean ("true"/"false")
    converged: str  # String representation of boolean ("true"/"false")

class ScenarioResult:
    """Dictionary containing the result of a Scenario action."""
    subcommand: str | None
    state: Literal["PASSED", "FAILED", "SKIPPED"]

class ScenariosResults:
    """Dictionary containing results of multiple Scenario runs."""
    name: str
    results: list[ScenarioResult]

Supporting Classes

Additional classes for managing scenario components.

class Platforms:
    """
    Defines the instances to be tested and their groups.
    
    Manages platform configuration, instance relationships,
    and group membership for test environments.
    """

class Scenario:
    """
    Represents a Molecule scenario.
    
    Contains scenario metadata, sequence definitions,
    and execution state for a complete test workflow.
    """

Usage Examples

Basic Configuration Setup

from molecule.config import Config
from molecule.types import MoleculeArgs, CommandArgs

# Create molecule arguments
mol_args = MoleculeArgs(
    debug=True,
    verbose=2,
    base_config=[],
    env_file=".env.yml"
)

# Create command arguments
cmd_args = CommandArgs(
    scenario_name="default",
    driver_name="default",
    destroy="always"
)

# Initialize configuration
config = Config(args=mol_args, command_args=cmd_args)

# Access configuration components
print(f"Driver: {config.driver.name}")
print(f"Scenario: {config.scenario.name}")
print(f"Platforms: {len(config.platforms.instances)}")

Configuration File Loading

# molecule.yml - Example configuration
dependency:
  name: galaxy
  enabled: true
  options:
    role-file: requirements.yml

driver:
  name: default
  options:
    managed: false

platforms:
  - name: instance-1
    groups:
      - web_servers
    children:
      - databases

provisioner:
  name: ansible
  config_options:
    defaults:
      host_key_checking: false
  ansible_args:
    - --diff
    - --extra-vars
    - test_var=value
  env:
    ANSIBLE_ROLES_PATH: ../roles

verifier:
  name: ansible
  enabled: true
  directory: verify

scenario:
  name: default
  test_sequence:
    - dependency
    - cleanup  
    - destroy
    - syntax
    - create
    - prepare
    - converge
    - idempotence
    - side_effect
    - verify
    - cleanup
    - destroy

Programmatic Configuration

from molecule.config import Config
from molecule.types import ConfigData, ScenarioData, PlatformData

# Create scenario configuration
scenario_data = ScenarioData(
    name="integration",
    test_sequence=[
        "create", "prepare", "converge", 
        "verify", "destroy"
    ],
    converge_sequence=["converge"],
    verify_sequence=["verify"]
)

# Create platform configuration
platform_data = PlatformData(
    name="ubuntu-20.04",
    groups=["test_servers"],
    children=[]
)

# Build complete configuration
config_data = ConfigData(
    scenario=scenario_data,
    platforms=[platform_data],
    # ... other configuration sections
)

Status Monitoring

from molecule.config import Config

config = Config()

# Get driver status
driver_status = config.driver.status()
for status in driver_status:
    print(f"Instance: {status.instance_name}")
    print(f"Created: {status.created}")
    print(f"Converged: {status.converged}")
    print(f"Driver: {status.driver_name}")

# Get scenario state
scenario_state = config.state
print(f"Scenario state: {scenario_state}")

Integration Notes

  • Configuration is loaded from molecule.yml files using YAML parsing
  • Environment variable substitution is supported in configuration files
  • Multiple configuration files can be merged using the --base-config option
  • Type safety is enforced through TypedDict classes for all configuration structures
  • Configuration validation uses JSON schema definitions
  • State persistence allows resuming test sequences from intermediate steps
  • Platform configuration supports complex inheritance and grouping scenarios

Install with Tessl CLI

npx tessl i tessl/pypi-molecule

docs

cli-commands.md

configuration.md

core-api.md

driver-system.md

exceptions.md

index.md

verifier-system.md

tile.json