-
Notifications
You must be signed in to change notification settings - Fork 42
API Usage
Broker exposes most of the same functionality the CLI provides through a Broker class. To use this class, simply import:
from broker import Broker
The Broker class largely accepts the same arguments as you would pass via the CLI. One key difference is that you need to use underscores instead of dashes. For example, a checkout at the CLI that looks like this
broker checkout --nick rhel7 --args-file tests/data/broker_args.json --environment="VAR1=val1,VAR2=val2"
could look like this in an API usage
rhel7_host = Broker(nick="rhel7", args_file="tests/data/broker_args.json", environment={"VAR1": "val1", "VAR2": "val2"}).checkout()
Broker will carry out its usual actions and package the resulting host in a Host object. This host object will also include some basic functionality, like the ability to execute ssh commands on the host. Executed ssh command results are packaged in a Results object containing status (return code), stdout, and stderr.
result = rhel7_host.execute("rpm -qa")
assert result.status == 0
assert "my-package" in result.stdout
The Broker class has a built-in context manager that automatically performs a checkout
upon enter and checkin
upon exit. It is the recommended way of interacting with Broker for host management.
In the below two lines of code:
- a container host is created (pulled if needed or applicable)
- a broker Host object is constructed
- the host object runs a command on the container
- output is checked
- the container is checked in
with Broker(container_host="ch-d:rhel7") as container_host:
assert container_host.hostname in container_host.execute("hostname").stdout
You are encouraged to build upon the existing Host
class broker provides but need to include it as a base class for Broker to work with it properly. This will allow you to build upon the base functionality Broker already provides while incorporating logic specific to your use cases.
Once you have a new class, you can let Broker know to use it during host construction.
from broker import Broker
from broker.hosts import Host
class MyHost(Host):
...
with Broker(..., host_class=MyHost) as my_host:
...
Sometimes you might want to define some behavior to occur after a host is checked out but before Broker gives it to you. Alternatively, you may want to define teardown logic that happens right before a host is checked in.
When using the Broker context manager, Broker will run any setup
or teardown
method defined on the Host object.
Broker will not pass any arguments to the setup
or teardown
methods, so they must not accept arguments.
<continued from above>
class MyHost(Host):
...
def setup(self):
self.register()
def teardown(self):
self.unregister()