importar os, sys, subproceso, textwrap, stat BASE = “/content/ansible_lab” si 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): “””Escribe un archivo dentado en BASE, creando directorios principales.””” 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): “””Ejecutar un comando de shell desde BASE, transmitir stdout, nunca generar.””” 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(“PASO 1: Instalación de ansible-core”) subprocess.run([sys.executable, “-m”, “pip”, “install”, “-q”, “ansible-core”]check=True) sh(“ansible –version”) write(“ansible.cfg”, “””
[defaults]
inventario = ./inventory.ini roles_path = ./roles biblioteca = ./library filter_plugins = ./filter_plugins vault_password_file = ./vault_pass.txt host_key_checking = Falso retry_files_enabled = Falso interpreter_python = auto_silent callback_result_format = yaml deprecation_warnings = Falso localhost_warning = Falsas vacas = 1
[privilege_escalation]
convertirse = False “””) escribir(“inventario.ini”, “””
[webservers]
web1 ansible_connection=local web2 ansible_connection=local
[dbservers]
db1 ansible_connection=local
[datacenter:children]
servidores web servidores db “””)
[defaults]
inventario = ./inventory.ini roles_path = ./roles biblioteca = ./library filter_plugins = ./filter_plugins vault_password_file = ./vault_pass.txt host_key_checking = Falso retry_files_enabled = Falso interpreter_python = auto_silent callback_result_format = yaml deprecation_warnings = Falso localhost_warning = Falsas vacas = 1
[privilege_escalation]
convertirse = False “””) escribir(“inventario.ini”, “””
[webservers]
web1 ansible_connection=local web2 ansible_connection=local
[dbservers]
db1 ansible_connection=local
[datacenter:children]
servidores web servidores db “””)