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_set Sets the values to be returned after the action finishes
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
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
is_relation_made Determine whether a relation is established by checking for presence of key(s).
juju_version Full version string (eg.
leader_get
leader_set
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
open_port Open a service network port
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 peer).
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
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 peer).
service_name The name service group this unit belongs to
status_get Retrieve the previously set juju workload state
status_set Set the workload state with a message
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_set(values)

Sets the values to be returned after the action finishes

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.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)
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)
charmhelpers.core.hookenv.leader_set(*args, **kwargs)
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.open_port(port, protocol='TCP')

Open a service network port

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 peer).

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.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 peer).

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

If the status-set 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.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