Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using the API - Documentation #1286

Open
KimJJarvis opened this issue Feb 4, 2025 · 1 comment
Open

Using the API - Documentation #1286

KimJJarvis opened this issue Feb 4, 2025 · 1 comment

Comments

@KimJJarvis
Copy link

Describe the bug

The API Reference -> Basic Localhost Example fails.

Traceback (most recent call last):
  File "/Users/kim/pyinfra-try/api2.py", line 43, in <module>
    host = state.hosts.inventory['@local']
           ^^^^^^^^^^^
AttributeError: 'State' object has no attribute 'hosts'

The reference to state.host does not seem to be documented in pyinfra.api.state.

Also, the code comments indicate that stdout and stderr should be present in the result of an add_op. However, the return values do not contain these fields. In the example result1 contains:

{   Host(10.66.240.21): OperationMeta(executed=True, success=True, hash=784a97bf1955d5f7a2b9dd6c1e371e17b73c42bc, commands=0)}

I searched the examples repo but was unable to find the output of an API operation being accessed at runtime. So, it is not immediately clear how this example should be fixed.

To Reproduce

Execute Basic Localhost Example. I changed inventory to get the example to run.

inventory = Inventory((["10.66.240.21"], {"ssh_user": "root", "ssh_password":"xxx"}))

Expected behavior

I expected the basic API example to work and I expected stdout to be available in the returned value.

There are two issues here:

  • Incorrect reference to state.host.inventory in the documented example.
  • stdout and stderr are not present in the OperationMeta returned from an API call.
@KimJJarvis
Copy link
Author

KimJJarvis commented Feb 5, 2025

The interface to OperationMeta and state have changed with v3. The following changes should be made to the example.

# add_op returns an OperationMeta for each op, letting you access stdout, stderr, etc. after they run
host = state.inventory.hosts['@local']
print(result1[host].did_change(), result1[host].stdout, result1[host].stderr)
print(result2[host].did_change(), result2[host].stdout, result2[host].stderr)

# We can also get facts for all the hosts
# https://docs.pyinfra.com/en/3.x/apidoc/pyinfra.api.facts.html
print(get_facts(state, Os))

PR #1287

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant