consul.api.agent module¶
- class consul.api.agent.Agent(agent)[source]¶
Bases:
objectThe Agent endpoints are used to interact with a local Consul agent. Usually, services and checks are registered with an agent, which then takes on the burden of registering with the Catalog and performing anti-entropy to recover from outages.
- services(filter_expr=None, token=None)[source]¶
Returns all the services that are registered with the local agent. These services were either provided through configuration files, or added dynamically using the HTTP API. It is important to note that the services known by the agent may be different than those reported by the Catalog. This is usually due to changes being made while there is no leader elected. The agent performs active anti-entropy, so in most situations everything will be in sync within a few seconds. :param filter_expr: Optional bexpr filter expression. :param token: token with node:read,service:read capability
- service_definition(service_id)[source]¶
Returns a service definition for a single instance that is registered with the local agent.
- checks(filter_expr=None, token=None)[source]¶
Returns all the checks that are registered with the local agent. These checks were either provided through configuration files, or added dynamically using the HTTP API. Similar to services, the checks known by the agent may be different than those reported by the Catalog. This is usually due to changes being made while there is no leader elected. The agent performs active anti-entropy, so in most situations everything will be in sync within a few seconds. :param filter_expr: Optional bexpr filter expression. :param token: token with node:read,service:read capability
- members(wan=False)[source]¶
Returns all the members that this agent currently sees. This may vary by agent, use the nodes api of Catalog to retrieve a cluster wide consistent view of members.
For agents running in server mode, setting wan to True returns the list of WAN members instead of the LAN members which is default.
- Parameters:
wan (bool)
- maintenance(enable, reason=None, token=None)[source]¶
The node maintenance endpoint can place the agent into “maintenance mode”.
enable is either ‘true’ or ‘false’. ‘true’ enables maintenance mode, ‘false’ disables maintenance mode.
reason is an optional string. This is simply to aid human operators.
- join(address, wan=False, token=None)[source]¶
This endpoint instructs the agent to attempt to connect to a given address.
address is the ip to connect to.
wan is either ‘true’ or ‘false’. For agents running in server mode, ‘true’ causes the agent to attempt to join using the WAN pool. Default is ‘false’.
- force_leave(node, prune=False, token=None)[source]¶
This endpoint instructs the agent to force a node into the left state. If a node fails unexpectedly, then it will be in a failed state. Once in the failed state, Consul will attempt to reconnect, and the services and checks belonging to that node will not be cleaned up. Forcing a node into the left state allows its old entries to be removed.
node is the node to change state for.
prune if set to True removes the node from the list of members entirely, instead of leaving it in the “left” state. Added in Consul 1.13.
- leave(token=None)[source]¶
Triggers a graceful leave and shutdown of the agent. It is used to ensure other nodes see the agent as “left” instead of “failed”. Nodes that leave are permanently removed from the cluster’s membership until they rejoin. For agents running in server mode, this also removes the node from the Raft peer set in a graceful manner.
Note that calling this will actually terminate the agent process.
Requires a token with agent:write ACL capability.
- Parameters:
token (str | None)
- reload(token=None)[source]¶
Instructs the agent to reload its configuration. Not all configuration options are reloadable, see the “Reloadable Configuration” section of the Consul documentation for the set of options that take effect via reload.
Requires a token with agent:write ACL capability.
- Parameters:
token (str | None)
- metrics(format_prometheus=False, token=None)[source]¶
Returns the metrics of the local agent for the most recent finished interval. By default, the response is returned as JSON.
format_prometheus if set to True, returns the metrics formatted as
text/plainin the Prometheus exposition format instead of JSON. Note that Prometheus output is only populated if the agent was started with a positive telemetry.prometheus_retention_time configured; otherwise Consul returns an empty 200 response body (with an X-Consul-Reason header explaining why) rather than an error.Requires a token with agent:read ACL capability.
- monitor(loglevel=None, logjson=False, token=None)[source]¶
Streams logs from the local agent until the connection is closed.
loglevel is an optional log level to filter on, e.g. “trace”, “debug”, “info”, “warn”, or “err”. Defaults to “info” on the Consul side if not supplied.
logjson if set to True, outputs each log line as JSON instead of Consul’s default plain-text log format.
Requires a token with agent:read ACL capability.
Warning
In real Consul this is a chunked/streaming endpoint that keeps the connection open indefinitely, only sending data as new log lines are produced; it does not close the connection on its own. This client implementation is a first pass and does not provide true streaming: it makes a single blocking GET request and returns whatever text body has accumulated once the connection ends. The sync client raises a read timeout once no log line has arrived for its connections_timeout, but as long as lines keep arriving, and with the async client by default, calling this method against a live, long-running agent can block forever unless the connection is closed by some other means (e.g. the agent shutting down, or a timeout enforced by the caller, such as running this call in a separate thread/task and cancelling it externally). Do not use this method in latency-sensitive or production code paths until true streaming support is added.
- class Service(agent)[source]¶
Bases:
object- register(name, service_id=None, address=None, port=None, tags=None, check=None, token=None, meta=None, weights=None, script=None, interval=None, ttl=None, http=None, timeout=None, enable_tag_override=False, extra_checks=None, replace_existing_checks=False, tagged_addresses=None, connect=None, kind=None, proxy=None, socket_path=None, locality=None)[source]¶
Add a new service to the local agent. There is more documentation on services here.
name is the name of the service.
If the optional service_id is not provided it is set to name. You cannot have duplicate service_id entries per agent, so it may be necessary to provide one.
address will default to the address of the agent if not provided.
An optional health check can be created for this service is one of `Check.script`_, `Check.http`_, `Check.tcp`_, `Check.ttl`_ or `Check.docker`_.
token is an optional `ACL token`_ to apply to this request. Note this call will return successful even if the token doesn’t have permissions to register this service.
meta specifies arbitrary KV metadata linked to the service formatted as {k1:v1, k2:v2}.
weights specifies weights for the service; default to {“Passing”: 1, “Warning”: 1}.
tagged_addresses specifies alternative addresses for the service, e.g. for use with Connect. Formatted as { “lan”: “<address>”, “wan”: “<address>” }.
connect specifies configuration for Connect. Formatted as { “sidecar_service”: {} }.
kind identifies this as a proxy/gateway instance rather than a plain service, e.g. “connect-proxy”, “mesh-gateway”, “terminating-gateway” or “ingress-gateway”.
proxy specifies the connect proxy configuration when kind is “connect-proxy”, e.g. {“DestinationServiceName”: “web”, “LocalServicePort”: 8080}.
socket_path specifies a Unix domain socket path the service listens on, as an alternative to address/port.
locality specifies the region/zone this service instance is deployed to, e.g. {“Region”: “us-west-1”, “Zone”: “us-west-1a”}.
script, interval, ttl, http, and timeout arguments are deprecated. use check instead.
replace_existing_checks Missing health checks from the request will be deleted from the agent. Using this parameter allows to idempotently register a service and its checks without having to manually deregister checks.
enable_tag_override is an optional bool that enable you to modify a service tags from servers(consul agent role server) Default is set to False. This option is only for >=v0.6.0 version on both agent and servers. for more information https://developer.hashicorp.com/consul/docs/fundamentals/service
- deregister(service_id, token=None)[source]¶
Used to remove a service from the local agent. The agent will take care of deregistering the service with the Catalog. If there is an associated check, that is also deregistered.
- maintenance(service_id, enable, reason=None, token=None)[source]¶
The service maintenance endpoint allows placing a given service into “maintenance mode”.
service_id is the id of the service that is to be targeted for maintenance.
enable is either ‘true’ or ‘false’. ‘true’ enables maintenance mode, ‘false’ disables maintenance mode.
reason is an optional string. This is simply to aid human operators.
- class Check(agent)[source]¶
Bases:
object- register(name, check=None, check_id=None, notes=None, service_id=None, token=None, script=None, interval=None, ttl=None, http=None, timeout=None)[source]¶
Register a new check with the local agent. More documentation on checks can be found here.
name is the name of the check.
check is one of `Check.script`_, `Check.http`_, `Check.tcp`_ `Check.ttl`_ or `Check.docker`_ and is required.
If the optional check_id is not provided it is set to name. check_id must be unique for this agent.
notes is not used by Consul, and is meant to be human readable.
Optionally, a service_id can be specified to associate a registered check with an existing service.
token is an optional `ACL token`_ to apply to this request. Note this call will return successful even if the token doesn’t have permissions to register this check.
script, interval, ttl, http, and timeout arguments are deprecated. use check instead.
Returns True on success.
- ttl_pass(check_id, notes=None, token=None)[source]¶
Mark a ttl based check as passing. Optional notes can be attached to describe the status of the check.
- class Connect(agent)[source]¶
Bases:
object- authorize(target, client_cert_uri, client_cert_serial, token=None)[source]¶
Tests whether a connection attempt is authorized between two services. More information is available here.
target is the name of the service that is being requested.
client_cert_uri The unique identifier for the requesting client.
client_cert_serial The colon-hex-encoded serial number for the requesting client cert.
- Parameters:
token (str | None)
- class Token(agent)[source]¶
Bases:
objectUsed to update the ACL tokens currently in use by the local agent. See here for more information.
Tokens set this way are only persisted to disk (surviving an agent restart) if the agent was started with acl.enable_token_persistence set to True.
- VALID_TOKEN_TYPES = frozenset({'agent', 'agent_recovery', 'config_file_service_registration', 'default', 'replication'})¶
type`.
- Type:
Literal path segments accepted by Consul for `PUT /v1/agent/token/
- set(token_type, secret, token=None)[source]¶
Sets the ACL token currently in use by the agent for token_type.
token_type must be one of “default”, “agent”, “agent_recovery”, “replication” or “config_file_service_registration”. Note that “agent_recovery” was named “agent_master” in Consul versions prior to 1.11.
secret is the secret ID of the ACL token to set. Pass an empty string to clear the currently configured token.
token is an optional ACL token to authenticate this request; it requires agent:write ACL capability.
Returns True on success.
- set_default(secret, token=None)[source]¶
Sets the default ACL token used for both client requests and to secure the agent’s internal RPCs itself.
- set_agent(secret, token=None)[source]¶
Sets the ACL token used for internal agent operations, such as service/check registration and anti-entropy syncs. Falls back to the “default” token if not set.
- set_agent_recovery(secret, token=None)[source]¶
Sets the ACL agent recovery token. This token can be used to access agent endpoints even when the servers are unreachable, e.g. for local troubleshooting. It was named “agent_master” in Consul versions prior to 1.11.