Often projects generate some client-side artifacts before running automations. So, in our case we’d like to generate some build files, then push them to remote servers by Pyinfra automation.
In order to achieve that we use:
Config script — this file is executed exclusively for a local machine and only once, and documentation states it’s a good place to generate client-side artifacts;
Automation scripts — general Pyinfra scripts which are executed for every host in your inventory.
The thing is that we’d like to generate a build artifact according to the argument provided in CLI:
I didn’t find any example how to access build-version in prepare.py script. Is it possible to access build-version in prepare.py config script somehow?
What have you tried?
I’ve tried to from pyinfra import host, but host object lacks of data field (seems like inventory is not initialized).
In Pyinfra, the --data argument allows you to pass custom data to be used during the automation process. However, it seems that in the prepare.py script, inventory and host data might not be initialized yet, which is why you are not able to access the host.data field directly.
To access the build-version argument in the prepare.py config script, you can make use of the pyinfra.local module, which provides access to CLI data. Here’s how you can achieve that:
Access CLI arguments in the config script: The CLI --data arguments are accessible globally in the automation scripts through the pyinfra.local.data dictionary. So, you should be able to access build-version in your prepare.py config script like this:
from pyinfra import local
build_version = local.data.get("build-version")
if build_version:
print(f"Build version provided: {build_version}")
else:
print("No build version provided")
This will allow you to access the build-version parameter in your prepare.py script. Since the config script is executed locally, using local.data will give you the values passed via the --data flag.
Running your Pyinfra command: You can run the command exactly as you planned: