Skip to main content

Creating an Infrahub client

Interfacing with Infrahub through the Python SDK is performed using a client object. A client object defines the Infrahub instance that you will be interfacing with. It provides methods to query data, create data, manage the schema and branches in Infrahub.

The Python SDK supports synchronous and asynchronous Python.

Asynchronous Python

The default client class InfrahubClient provides the asynchronous version.

from infrahub_sdk import InfrahubClient
client = InfrahubClient(address="http://localhost:8000")

Synchronous Python

The InfrahubClientSync class provides the synchronous version.

from infrahub_sdk import InfrahubClientSync
client = InfrahubClientSync(address="http://localhost:8000")

Authentication

The SDK can use API Tokens or JWT Tokens to authenticate with the REST API and GraphQL.

API tokens

The API token can be provided using a Config object or you can define it as the INFRAHUB_API_TOKEN environment variable.

from infrahub_sdk import Config, InfrahubClient
client = await InfrahubClient(config=Config(api_token="token"))
client = await InfrahubClient() # token is read from the INFRAHUB_API_TOKEN environment variable

JWT tokens

The username and password of the user can be provided using a Config object or you can define them using the INFRAHUB_USERNAME and INFRAHUB_PASSWORD environment variables. The usage of JWT Tokens is completely transparent to the user, including the process of refreshing the JWT token.

from infrahub_sdk import Config, InfrahubClient
client = await InfrahubClient(config=Config(username="admin", password="infrahub"))
client = await InfrahubClient() # token is read from the INFRAHUB_USERNAME and INFRAHUB_PASSWORD environment variable

Configuring the client object

The client object can be configured by providing a Config object. Here we will show you how to enable the client to print out all of the GraphQL queries it will send to Infrahub.

from infrahub_sdk import Config, InfrahubClient
config = Config(echo_graphql_queries=True)
client = await InfrahubClient(config=config)

More details on the available configuration options can be found SDK configuration reference.

Setting the default branch

The client object can be configured to use a specific branch in Infrahub. By default the client will use the main branch, but you can change this to be any other branch. The methods, provided by the client, have a branch argument which allow you to specific against which branch you want to execute the functionality provided by the branch. If this argument is not provided then the default_branch of the client will be used.

from infrahub_sdk import InfrahubClient, Config
config = Config(default_branch="other-branch")
client_other_branch = InfrahubClient(config=config)

tag_other_branch = await client_other_branch.get(kind="BuiltinTag", name__value="RED")
tag_main_branch = await client_other_branch.get(kind="BuiltinTag", name__value="RED", branch="main")