charmhelpers.core.hookenv

Config A dictionary representation of the charm’s config.yaml, with some
Hooks A convenient handler for hook functions.
Serializable Wrapper, an object that can be serialized to yaml or json
UnregisteredHookError Raised when an undefined hook is called
action_fail Sets the action status to failed and sets the error message.
action_get Gets the value of an action parameter, or all key/value param pairs
action_name Get the name of the currently executing action.
action_set Sets the values to be returned after the action finishes
action_tag Get the tag for the currently executing action.
action_uuid Get the UUID of the currently executing action.
add_metric Add metric values.
application_version_set Charm authors may trigger this command from any hook to output what version of the application is running.
atexit Schedule a callback to run on successful hook completion.
atstart Schedule a callback to run before the main hook.
cached Cache return values for multiple executions of func + args
charm_dir Return the root directory of the current charm
charm_name Get the name of the current charm as is specified on metadata.yaml
close_port Close a service network port
close_ports Close a range of service network ports
config Juju charm configuration
execution_environment A convenient bundling of the current execution context
flush Flushes any entries from function cache where the
has_juju_version Return True if the Juju version is at least the provided version
hook_name The name of the currently executing hook
in_relation_hook Determine whether we’re running in a relation hook
interface_to_relations Given an interface, return a list of relation names for the current charm that use that interface.
is_leader Does the current unit hold the juju leadership
is_relation_made Determine whether a relation is established by checking for presence of key(s).
juju_version Full version string (eg.
leader_get Juju leader get value(s)
leader_set Juju leader set value(s)
local_unit Local unit ID
log Write a message to the juju log
metadata Get the current charm metadata.yaml contents as a python object
meter_info Get the meter status information, if running in the meter-status-changed hook.
meter_status Get the meter status, if running in the meter-status-changed hook.
network_get_primary_address Retrieve the primary network address for a named binding
open_port Open a service network port
open_ports Opens a range of service network ports
payload_register is used while a hook is running to let Juju know that a
payload_status_set is used to update the current status of a registered payload.
payload_unregister is used while a hook is running to let Juju know
peer_relation_id Get the peers relation id if a peers relation has been joined, else None.
related_units A list of related units
relation_clear Clears any relation data already set on relation r_id
relation_for_unit Get the json represenation of a unit’s relation
relation_get Get relation information
relation_id The relation ID for the current or a specified relation
relation_ids A list of relation_ids
relation_set Set relation information for the current unit
relation_to_interface Given the name of a relation, return the interface that relation uses.
relation_to_role_and_interface Given the name of a relation, return the role and the name of the interface that relation uses (where role is one of provides, requires, or peers).
relation_type The scope for the current relation hook
relation_types Get a list of relation types supported by this charm
relations Get a nested dictionary of relation data for all related units
relations_for_id Get relations of a specific relation ID
relations_of_type Get relations of a specific type
remote_service_name The remote service name for a given relation-id (or the current relation)
remote_unit The remote unit for the current relation hook
resource_get used to fetch the resource path of the given name.
role_and_interface_to_relations Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of provides, requires, or peers).
service_name The name service group this unit belongs to
status_get Retrieve the previously set juju workload state and message
status_set Set the workload state with a message
storage_get Get storage attributes
storage_list List the storage IDs for the unit
translate_exc
unit_get Get the unit ID for the remote unit
unit_private_ip Get this unit’s private IP address
unit_public_ip Get this unit’s public IP address

Interactions with the Juju environment

class charmhelpers.core.hookenv.Config(*args, **kw)

Bases: dict

A dictionary representation of the charm’s config.yaml, with some extra features:

  • See which values in the dictionary have changed since the previous hook.
  • For values that have changed, see what the previous value was.
  • Store arbitrary data for use in a later hook.

NOTE: Do not instantiate this object directly - instead call hookenv.config(), which will return an instance of Config.

Example usage:

>>> # inside a hook
>>> from charmhelpers.core import hookenv
>>> config = hookenv.config()
>>> config['foo']
'bar'
>>> # store a new key/value for later use
>>> config['mykey'] = 'myval'


>>> # user runs `juju set mycharm foo=baz`
>>> # now we're inside subsequent config-changed hook
>>> config = hookenv.config()
>>> config['foo']
'baz'
>>> # test to see if this val has changed since last hook
>>> config.changed('foo')
True
>>> # what was the previous value?
>>> config.previous('foo')
'bar'
>>> # keys/values that we add are preserved across hooks
>>> config['mykey']
'myval'
CONFIG_FILE_NAME = '.juju-persistent-config'
changed(key)

Return True if the current value for this key is different from the previous value.

load_previous(path=None)

Load previous copy of config from disk.

In normal usage you don’t need to call this method directly - it is called automatically at object initialization.

Parameters:path – File path from which to load the previous config. If None, config is loaded from the default location. If path is specified, subsequent save() calls will write to the same path.
previous(key)

Return previous value for this key, or None if there is no previous value.

save()

Save this config to disk.

If the charm is using the Services Framework or :meth:’@hook <Hooks.hook>’ decorator, this is called automatically at the end of successful hook execution. Otherwise, it should be called directly by user code.

To disable automatic saves, set implicit_save=False on this instance.

class charmhelpers.core.hookenv.Hooks(config_save=None)

Bases: object

A convenient handler for hook functions.

Example:

hooks = Hooks()

# register a hook, taking its name from the function name
@hooks.hook()
def install():
    pass  # your code here

# register a hook, providing a custom hook name
@hooks.hook("config-changed")
def config_changed():
    pass  # your code here

if __name__ == "__main__":
    # execute a hook based on the name the program is called by
    hooks.execute(sys.argv)
execute(args)

Execute a registered hook based on args[0]

hook(*hook_names)

Decorator, registering them as hooks

register(name, function)

Register a hook

class charmhelpers.core.hookenv.Serializable(obj)

Bases: UserDict.UserDict

Wrapper, an object that can be serialized to yaml or json

json()

Serialize the object to json

yaml()

Serialize the object to yaml

exception charmhelpers.core.hookenv.UnregisteredHookError

Bases: exceptions.Exception

Raised when an undefined hook is called

charmhelpers.core.hookenv.action_fail(message)

Sets the action status to failed and sets the error message.

The results set by action_set are preserved.

charmhelpers.core.hookenv.action_get(*args, **kwargs)

Gets the value of an action parameter, or all key/value param pairs

charmhelpers.core.hookenv.action_name()

Get the name of the currently executing action.

charmhelpers.core.hookenv.action_set(values)

Sets the values to be returned after the action finishes

charmhelpers.core.hookenv.action_tag()

Get the tag for the currently executing action.

charmhelpers.core.hookenv.action_uuid()

Get the UUID of the currently executing action.

charmhelpers.core.hookenv.add_metric(*args, **kwargs)

Add metric values. Values may be expressed with keyword arguments. For metric names containing dashes, these may be expressed as one or more ‘key=value’ positional arguments. May only be called from the collect-metrics hook.

charmhelpers.core.hookenv.application_version_set(version)

Charm authors may trigger this command from any hook to output what version of the application is running. This could be a package version, for instance postgres version 9.5. It could also be a build number or version control revision identifier, for instance git sha 6fb7ba68.

charmhelpers.core.hookenv.atexit(callback, *args, **kwargs)

Schedule a callback to run on successful hook completion.

Callbacks are run in the reverse order that they were added.

charmhelpers.core.hookenv.atstart(callback, *args, **kwargs)

Schedule a callback to run before the main hook.

Callbacks are run in the order they were added.

This is useful for modules and classes to perform initialization and inject behavior. In particular:

  • Run common code before all of your hooks, such as logging the hook name or interesting relation data.
  • Defer object or module initialization that requires a hook context until we know there actually is a hook context, making testing easier.
  • Rather than requiring charm authors to include boilerplate to invoke your helper’s behavior, have it run automatically if your object is instantiated or module imported.

This is not at all useful after your hook framework as been launched.

charmhelpers.core.hookenv.cached(func)

Cache return values for multiple executions of func + args

For example:

@cached
def unit_get(attribute):
    pass

unit_get('test')

will cache the result of unit_get + ‘test’ for future calls.

charmhelpers.core.hookenv.charm_dir()

Return the root directory of the current charm

charmhelpers.core.hookenv.charm_name(*args, **kwargs)

Get the name of the current charm as is specified on metadata.yaml

charmhelpers.core.hookenv.close_port(port, protocol='TCP')

Close a service network port

charmhelpers.core.hookenv.close_ports(start, end, protocol='TCP')

Close a range of service network ports

charmhelpers.core.hookenv.config(*args, **kwargs)

Juju charm configuration

charmhelpers.core.hookenv.execution_environment()

A convenient bundling of the current execution context

charmhelpers.core.hookenv.flush(key)

Flushes any entries from function cache where the key is found in the function+args

charmhelpers.core.hookenv.has_juju_version(*args, **kwargs)

Return True if the Juju version is at least the provided version

charmhelpers.core.hookenv.hook_name()

The name of the currently executing hook

charmhelpers.core.hookenv.in_relation_hook()

Determine whether we’re running in a relation hook

charmhelpers.core.hookenv.interface_to_relations(*args, **kwargs)

Given an interface, return a list of relation names for the current charm that use that interface.

Returns:A list of relation names.
charmhelpers.core.hookenv.is_leader(*args, **kwargs)

Does the current unit hold the juju leadership

Uses juju to determine whether the current unit is the leader of its peers

charmhelpers.core.hookenv.is_relation_made(*args, **kwargs)

Determine whether a relation is established by checking for presence of key(s). If a list of keys is provided, they must all be present for the relation to be identified as made

charmhelpers.core.hookenv.juju_version(*args, **kwargs)

Full version string (eg. ‘1.23.3.1-trusty-amd64’)

charmhelpers.core.hookenv.leader_get(*args, **kwargs)

Juju leader get value(s)

charmhelpers.core.hookenv.leader_set(*args, **kwargs)

Juju leader set value(s)

charmhelpers.core.hookenv.local_unit()

Local unit ID

charmhelpers.core.hookenv.log(message, level=None)

Write a message to the juju log

charmhelpers.core.hookenv.metadata(*args, **kwargs)

Get the current charm metadata.yaml contents as a python object

charmhelpers.core.hookenv.meter_info()

Get the meter status information, if running in the meter-status-changed hook.

charmhelpers.core.hookenv.meter_status()

Get the meter status, if running in the meter-status-changed hook.

charmhelpers.core.hookenv.network_get_primary_address(*args, **kwargs)

Retrieve the primary network address for a named binding

Parameters:binding – string. The name of a relation of extra-binding
Returns:string. The primary IP address for the named binding
Raise:NotImplementedError if run on Juju < 2.0
charmhelpers.core.hookenv.open_port(port, protocol='TCP')

Open a service network port

charmhelpers.core.hookenv.open_ports(start, end, protocol='TCP')

Opens a range of service network ports

charmhelpers.core.hookenv.payload_register(*args, **kwargs)

is used while a hook is running to let Juju know that a payload has been started.

charmhelpers.core.hookenv.payload_status_set(*args, **kwargs)

is used to update the current status of a registered payload. The <class> and <id> provided must match a payload that has been previously registered with juju using payload-register. The <status> must be one of the follow: starting, started, stopping, stopped

charmhelpers.core.hookenv.payload_unregister(*args, **kwargs)

is used while a hook is running to let Juju know that a payload has been manually stopped. The <class> and <id> provided must match a payload that has been previously registered with juju using payload-register.

charmhelpers.core.hookenv.peer_relation_id(*args, **kwargs)

Get the peers relation id if a peers relation has been joined, else None.

charmhelpers.core.hookenv.related_units(*args, **kwargs)

A list of related units

charmhelpers.core.hookenv.relation_clear(r_id=None)

Clears any relation data already set on relation r_id

charmhelpers.core.hookenv.relation_for_unit(*args, **kwargs)

Get the json represenation of a unit’s relation

charmhelpers.core.hookenv.relation_get(*args, **kwargs)

Get relation information

charmhelpers.core.hookenv.relation_id(*args, **kwargs)

The relation ID for the current or a specified relation

charmhelpers.core.hookenv.relation_ids(*args, **kwargs)

A list of relation_ids

charmhelpers.core.hookenv.relation_set(relation_id=None, relation_settings=None, **kwargs)

Set relation information for the current unit

charmhelpers.core.hookenv.relation_to_interface(*args, **kwargs)

Given the name of a relation, return the interface that relation uses.

Returns:The interface name, or None.
charmhelpers.core.hookenv.relation_to_role_and_interface(*args, **kwargs)

Given the name of a relation, return the role and the name of the interface that relation uses (where role is one of provides, requires, or peers).

Returns:A tuple containing (role, interface), or (None, None).
charmhelpers.core.hookenv.relation_type()

The scope for the current relation hook

charmhelpers.core.hookenv.relation_types(*args, **kwargs)

Get a list of relation types supported by this charm

charmhelpers.core.hookenv.relations(*args, **kwargs)

Get a nested dictionary of relation data for all related units

charmhelpers.core.hookenv.relations_for_id(*args, **kwargs)

Get relations of a specific relation ID

charmhelpers.core.hookenv.relations_of_type(*args, **kwargs)

Get relations of a specific type

charmhelpers.core.hookenv.remote_service_name(*args, **kwargs)

The remote service name for a given relation-id (or the current relation)

charmhelpers.core.hookenv.remote_unit()

The remote unit for the current relation hook

charmhelpers.core.hookenv.resource_get(*args, **kwargs)

used to fetch the resource path of the given name.

<name> must match a name of defined resource in metadata.yaml

returns either a path or False if resource not available

charmhelpers.core.hookenv.role_and_interface_to_relations(*args, **kwargs)

Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of provides, requires, or peers).

Returns:A list of relation names.
charmhelpers.core.hookenv.service_name()

The name service group this unit belongs to

charmhelpers.core.hookenv.status_get()

Retrieve the previously set juju workload state and message

If the status-get command is not found then assume this is juju < 1.23 and return ‘unknown’, “”

charmhelpers.core.hookenv.status_set(workload_state, message)

Set the workload state with a message

Use status-set to set the workload state with a message which is visible to the user via juju status. If the status-set command is not found then assume this is juju < 1.23 and juju-log the message unstead.

workload_state – valid juju workload state. message – status update message

charmhelpers.core.hookenv.storage_get(*args, **kwargs)

Get storage attributes

charmhelpers.core.hookenv.storage_list(*args, **kwargs)

List the storage IDs for the unit

charmhelpers.core.hookenv.translate_exc(from_exc, to_exc)
charmhelpers.core.hookenv.unit_get(*args, **kwargs)

Get the unit ID for the remote unit

charmhelpers.core.hookenv.unit_private_ip()

Get this unit’s private IP address

charmhelpers.core.hookenv.unit_public_ip()

Get this unit’s public IP address