Generative AI
How to Design an Ansible End-to-End Automation Lab with Playbooks, Inventories, Roles, Vault, Dynamic Inventory, and Custom Modules

import os, sys, subprocess, textwrap, stat
BASE = "/content/ansible_lab" if os.path.isdir("/content") else os.path.expanduser("~/ansible_lab")
os.makedirs(BASE, exist_ok=True)
ENV = os.environ.copy()
ENV["ANSIBLE_CONFIG"] = os.path.join(BASE, "ansible.cfg")
ENV["ANSIBLE_FORCE_COLOR"] = "1"
ENV["PY_COLORS"] = "0"
def banner(title):
print("n" + "=" * 78 + f"n {title}n" + "=" * 78)
def write(relpath, content):
"""Write a dedented file under BASE, creating parent dirs."""
path = os.path.join(BASE, relpath)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(textwrap.dedent(content).lstrip("n"))
return path
def sh(cmd, title=None):
"""Run a shell command from BASE, stream stdout, never raise."""
if title:
banner(title)
print(f"$ {cmd}n")
p = subprocess.run(cmd, shell=True, cwd=BASE, env=ENV,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
print(p.stdout)
return p.returncode
banner("STEP 1 — Installing ansible-core")
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "ansible-core"], check=True)
sh("ansible --version")
write("ansible.cfg", """
[defaults]
inventory = ./inventory.ini
roles_path = ./roles
library = ./library
filter_plugins = ./filter_plugins
vault_password_file = ./vault_pass.txt
host_key_checking = False
retry_files_enabled = False
interpreter_python = auto_silent
callback_result_format = yaml
deprecation_warnings = False
localhost_warning = False
nocows = 1
[privilege_escalation]
become = False
""")
write("inventory.ini", """
[webservers]
web1 ansible_connection=local
web2 ansible_connection=local
[dbservers]
db1 ansible_connection=local
[datacenter:children]
webservers
dbservers
""")



