def test_nested_op_api(self): inventory = make_inventory() state = State(inventory, Config()) connect_all(state) somehost = inventory.get_host("somehost") ctx_state.set(state) ctx_host.set(somehost) pyinfra.is_cli = True try: outer_result = server.shell(commands="echo outer") assert outer_result.combined_output_lines is None def callback(): inner_result = server.shell(commands="echo inner") assert inner_result.combined_output_lines is not None python.call(function=callback) assert len(state.get_op_order()) == 2 run_ops(state) assert len(state.get_op_order()) == 3 assert state.results[somehost]["success_ops"] == 3 assert outer_result.combined_output_lines is not None disconnect_all(state) finally: pyinfra.is_cli = False
assert status is True # ensure the command executed OK if 'Vagrant ' not in str(stdout): raise Exception( '`{}` did not work as expected.stdout:{} stderr:{}'.format( command, stdout, stderr)) if host.fact.linux_name == 'Ubuntu': apt.packages( {'Install required packages'}, ['wget', 'unzip', 'python3'], update=True, ) files.download( {'Download the Vagrantup Downloads page'}, 'https://www.vagrantup.com/downloads.html', '/tmp/downloads.html', ) server.script_template( {'Use wget to download and unzip to /usr/local/bin'}, 'templates/download_vagrant.bash.j2', ) python.call( {'Verify vagrant is installed by running version command'}, verify_vagrant, )
apt.repo( {'Install VirtualBox repo'}, 'deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name), ) # install kernel headers # Note: host.fact.os_version is the same as `uname -r` (ex: '4.15.0-72-generic') apt.packages( { 'Install VirtualBox version {} and ' 'kernel headers for {}'.format(virtualbox_version, host.fact.os_version), }, [ 'virtualbox-{}'.format(virtualbox_version), 'linux-headers-{}'.format(host.fact.os_version), ], update=True, ) server.shell( {'Run vboxconfig which will stop/start VirtualBox services and build kernel modules'}, '/sbin/vboxconfig', ) python.call( {'Verify VirtualBox version'}, verify_virtualbox_version, version=virtualbox_version, )
code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME') print(linux_id, code_name) apt.repo( {'Add the Docker CE apt repo'}, ( 'deb [arch=amd64] https://download.docker.com/linux/' '{} ' '{} stable'.format(linux_id, code_name) ), filename='docker-ce-stable', ) apt.packages( {'Ensure Docker CE is installed'}, [ 'docker-ce', 'docker-ce-cli', 'containerd.io', ], update=True, ) init.service( {'Ensure docker service is running'}, 'docker', running=True, enabled=True, ) python.call(check_docker_works)
) pip.packages( name='Install virtualenv using pip', packages='virtualenv', ) pip.virtualenv( name='Create a virtualenv', path='/usr/local/bin/venv', ) # use that virtualenv to install pyinfra pip.packages( name='Install pyinfra into a virtualenv', packages='pyinfra', virtualenv='/usr/local/bin/venv', ) # Show that we can actually run the pyinfra command from that virtualenv def run_pyinfra_version(state, host): status, stdout, stderr = host.run_shell_command( '/usr/local/bin/venv/bin/pyinfra --version', env={'LC_ALL': 'C.UTF-8', 'LANG': 'C.UTF-8,'}, ) assert status, 'pyinfra command failed: {0}'.format((stdout, stderr)) assert 'pyinfra: ' in stdout[0] python.call(run_pyinfra_version) # noqa: E305
client_psk = f.read().strip() addresses = [f"{NETWORK[i]}/{NETWORK.max_prefixlen}"] if IPV6NETWORK: addresses.append( f"{IPV6NETWORK[102*16*16*16*16 + i]}/{IPV6NETWORK.max_prefixlen}" ) WG_CONF.write(f'''\ [Peer] PublicKey = {client_pub} PresharedKey = {client_psk} AllowedIPs = {', '.join(addresses)} ''') python.call( name='Generate client wireguard config', function=generate_client_config, ) python.call( name='Generate wireguard config', function=generate_config, ) files.put( name='Upload wireguard config', src=WG_CONF, dest=f'/etc/wireguard/{WG_IF}.conf', ) files.put(name='Create wireguard interface configuration', src=io.StringIO(f'''\
from pyinfra.operations import python # Tip: Can run try it out using: 'pyinfra @docker/python python.py' SUDO = True def my_callback(state, host, hello=None): command = 'echo hello' if hello: command = command + ' ' + hello status, stdout, stderr = host.run_shell_command(state, command=command, sudo=SUDO) assert status is True # ensure the command executed OK if 'hello ' not in str(stdout): raise Exception( '`{}` problem with callback stdout:{} stderr:{}'.format( command, stdout, stderr)) python.call(my_callback, hello='world')
apt.repo( name="Install VirtualBox repo", src="deb https://download.virtualbox.org/virtualbox/debian {} contrib".format(code_name), ) # install kernel headers # Note: host.get_fact(OsVersion) is the same as `uname -r` (ex: '4.15.0-72-generic') apt.packages( { "Install VirtualBox version {} and " "kernel headers for {}".format(virtualbox_version, host.get_fact(OsVersion)), }, [ "virtualbox-{}".format(virtualbox_version), "linux-headers-{}".format(host.get_fact(OsVersion)), ], update=True, ) server.shell( name="Run vboxconfig which will stop/start VirtualBox services and build kernel modules", commands="/sbin/vboxconfig", ) python.call( name="Verify VirtualBox version", function=verify_virtualbox_version, version=virtualbox_version, )
def nested_op(): sleep(randint(1, 10) * 0.01) server.shell( name="First nested operation", commands="echo first_nested_operation", ) if host.name == "anotherhost": sleep(randint(1, 10) * 0.01) server.shell( name="Second nested anotherhost operation", commands="echo first_nested_operation", ) if host.name == "somehost": server.shell( name="Second nested somehost operation", commands="echo first_nested_operation", ) python.call(name="Function call operation", function=nested_op) sleep(randint(1, 10) * 0.01) server.shell( name="Third main operation", commands="echo third_main_op", )
from pyinfra.operations import python # Tip: Can run try it out using: 'pyinfra @docker/python python.py' def my_callback(state, host, hello=None): command = "echo hello" if hello: command = command + " " + hello status, stdout, stderr = host.run_shell_command(state, command=command) assert status is True # ensure the command executed OK if "hello " not in str(stdout): raise Exception( "`{}` problem with callback stdout:{} stderr:{}".format( command, stdout, stderr), ) python.call(my_callback, hello="world")