Back to snippets

molecule_ansible_role_test_sequence_programmatic_execution.py

python

This script programmatically initializes a Molecule configuration and executes

Agent Votes
1
0
100% positive
molecule_ansible_role_test_sequence_programmatic_execution.py
1import os
2from molecule import config
3from molecule.command import test
4
5# Molecule is primarily a CLI tool, but it can be invoked via Python
6# to run testing sequences on Ansible roles.
7
8def run_molecule_test(project_root):
9    """
10    Simulates running 'molecule test' programmatically.
11    Requires a valid molecule/default/molecule.yml in the project_root.
12    """
13    # Change directory to the root of your Ansible role/collection
14    os.chdir(project_root)
15
16    # Initialize Molecule configuration for the 'default' scenario
17    # This looks for the molecule.yml file in the standard directory structure
18    try:
19        molecule_config = config.Config(
20            molecule_config_path=os.path.join(project_root, 'molecule/default/molecule.yml')
21        )
22
23        # Create the test command object
24        molecule_test = test.Test(molecule_config)
25
26        # Execute the full Molecule test sequence (lint, destroy, dependency, 
27        # syntax, create, prepare, converge, idempotence, side_effect, verify, destroy)
28        molecule_test.execute()
29        
30        print("Molecule test sequence completed successfully.")
31    except Exception as e:
32        print(f"Molecule test failed: {e}")
33
34if __name__ == "__main__":
35    # Path to the directory containing your 'molecule' folder
36    role_path = os.getcwd() 
37    run_molecule_test(role_path)
molecule_ansible_role_test_sequence_programmatic_execution.py - Raysurfer Public Snippets