juju.model

Summary

CharmArchiveGenerator

Create a Zip archive of a local charm directory for upload to a controller.

Methods:

CharmStore
Async wrapper around theblues.charmstore.CharmStore
Model

The main API for interacting with a Juju model.

Methods:

ModelEntity

An object in the Model tree

Methods:

ModelObserver

Base class for creating observers that react to changes in a model.

Methods:

ModelState

Holds the state of the model, including the delta history of all entities in the model.

Methods:

Reference

class juju.model.CharmArchiveGenerator(path)[source]

Bases: object

Create a Zip archive of a local charm directory for upload to a controller.

This is used automatically by Model.add_local_charm_dir.

make_archive(path)[source]

Create archive of directory and write to path.

Parameters:path – Path to archive

Ignored:

* build/* - This is used for packing the charm itself and any
              similar tasks.
* */.*    - Hidden files are all ignored for now.  This will most
              likely be changed into a specific ignore list
              (.bzr, etc)
class juju.model.CharmStore(loop, cs_timeout=20)[source]

Bases: object

Async wrapper around theblues.charmstore.CharmStore

class juju.model.Model(loop=None, max_frame_size=None, bakery_client=None, jujudata=None)[source]

Bases: object

The main API for interacting with a Juju model.

add_local_charm(charm_file, series, size=None)[source]

Upload a local charm archive to the model.

Returns the ‘local:…’ url that should be used to deploy the charm.

Parameters:
  • charm_file – Path to charm zip archive
  • series – Charm series
  • size – Size of the archive, in bytes
Return str:

‘local:…’ url for deploying the charm

Raises:

JujuError if the upload fails

Uses an https endpoint at the same host:port as the wss. Supports large file uploads.

Warning

This method will block. Consider using add_local_charm_dir() instead.

coroutine add_local_charm_dir(charm_dir, series)[source]

Upload a local charm to the model.

This will automatically generate an archive from the charm dir.

Parameters:
  • charm_dir – Path to the charm directory
  • series – Charm series
coroutine add_machine(spec=None, constraints=None, disks=None, series=None)[source]

Start a new, empty machine and optionally a container, or add a container to a machine.

Parameters:
  • spec (str) –

    Machine specification Examples:

    (None) - starts a new machine
    'lxd' - starts a new machine with one lxd container
    'lxd:4' - starts a new lxd container on machine 4
    'ssh:user@10.10.0.3:/path/to/private/key' - manually provision
    a machine with ssh and the private key used for authentication
    'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS
    'maas2.name' - acquire machine maas2.name on MAAS
    
  • constraints (dict) –

    Machine constraints, which can contain the the following keys:

    arch : str
    container : str
    cores : int
    cpu_power : int
    instance_type : str
    mem : int
    root_disk : int
    spaces : list(str)
    tags : list(str)
    virt_type : str
    

    Example:

    constraints={
        'mem': 256 * MB,
        'tags': ['virtual'],
    }
    
  • disks (list) –

    List of disk constraint dictionaries, which can contain the following keys:

    count : int
    pool : str
    size : int
    

    Example:

    disks=[{
        'pool': 'rootfs',
        'size': 10 * GB,
        'count': 1,
    }]
    
  • series (str) – Series, e.g. ‘xenial’

Supported container types are: lxd, kvm

When deploying a container to an existing machine, constraints cannot be used.

add_observer(callable_, entity_type=None, action=None, entity_id=None, predicate=None)[source]

Register an “on-model-change” callback

Once the model is connected, callable_ will be called each time the model changes. callable_ should be Awaitable and accept the following positional arguments:

delta - An instance of juju.delta.EntityDelta
containing the raw delta data recv’d from the Juju websocket.
old_obj - If the delta modifies an existing object in the model,
old_obj will be a copy of that object, as it was before the delta was applied. Will be None if the delta creates a new entity in the model.
new_obj - A copy of the new or updated object, after the delta
is applied. Will be None if the delta removes an entity from the model.

model - The Model itself.

Events for which callable_ is called can be specified by passing entity_type, action, and/or entitiy_id filter criteria, e.g.:

add_observer(
    myfunc,
    entity_type='application', action='add', entity_id='ubuntu')

For more complex filtering conditions, pass a predicate function. It will be called with a delta as its only argument. If the predicate function returns True, the callable_ will be called.

coroutine add_relation(relation1, relation2)[source]

Add a relation between two applications.

Parameters:
  • relation1 (str) – ‘<application>[:<relation_name>]’
  • relation2 (str) – ‘<application>[:<relation_name>]’
add_space(name, *cidrs)[source]

Add a new network space.

Adds a new space with the given name and associates the given (optional) list of existing subnet CIDRs with it.

Parameters:
  • name (str) – Name of the space
  • *cidrs

    Optional list of existing subnet CIDRs

coroutine add_ssh_key(user, key)[source]

Add a public SSH key to this model.

Parameters:
  • user (str) – The username of the user
  • key (str) – The public ssh key
coroutine add_ssh_keys(user, key)

Add a public SSH key to this model.

Parameters:
  • user (str) – The username of the user
  • key (str) – The public ssh key
add_subnet(cidr_or_id, space, *zones)[source]

Add an existing subnet to this model.

Parameters:
  • cidr_or_id (str) – CIDR or provider ID of the existing subnet
  • space (str) – Network space with which to associate
  • *zones (str) –

    Zone(s) in which the subnet resides

all_units_idle()[source]

Return True if all units are idle.

application_offers

Return a map of application-name:Application for all applications offers currently in the model.

applications

Return a map of application-name:Application for all applications currently in the model.

block(*commands)[source]

Add a new block to this model.

Parameters:*commands (str) –

The commands to block. Valid values are ‘all-changes’, ‘destroy-model’, ‘remove-object’

coroutine block_until(*conditions, timeout=None, wait_period=0.5)[source]

Return only after all conditions are true.

Raises websockets.ConnectionClosed if disconnected.

charmstore
coroutine connect(*args, **kwargs)[source]

Connect to a juju model.

This supports two calling conventions:

The model and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a model_name is specified, or if the endpoint and uuid are not.

Otherwise, all of the endpoint, uuid, and authentication information (username and password, or bakery_client and/or macaroons) are required.

If a single positional argument is given, it will be assumed to be the model_name. Otherwise, the first positional argument, if any, must be the endpoint.

Available parameters are:

Parameters:
  • model_name – Format [controller:][user/]model
  • endpoint (str) – The hostname:port of the controller to connect to.
  • uuid (str) – The model UUID to connect to.
  • username (str) – The username for controller-local users (or None to use macaroon-based login.)
  • password (str) – The password for controller-local users.
  • cacert (str) – The CA certificate of the controller (PEM formatted).
  • bakery_client (httpbakery.Client) – The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used.
  • macaroons (list) – List of macaroons to load into the bakery_client.
  • loop (asyncio.BaseEventLoop) – The event loop to use for async operations.
  • max_frame_size (int) – The maximum websocket frame size to allow.
  • specified_facades – Overwrite the facades with a series of specified facades.
coroutine connect_current()[source]

Deprecated since version 0.6.2: Use connect() instead.

coroutine connect_model(model_name)[source]

Deprecated since version 0.6.2: Use connect(model_name=model_name) instead.

connection()[source]

Return the current Connection object. It raises an exception if the Model is disconnected

coroutine consume(endpoint, application_alias='', controller_name=None)[source]

Adds a remote offer to the model. Relations can be created later using “juju relate”.

create_backup(note=None, no_download=False)[source]

Create a backup of this model.

Parameters:
  • note (str) – A note to store with the backup
  • no_download (bool) – Do not download the backup archive
Return str:

Path to downloaded archive

coroutine create_offer(endpoint, offer_name=None, application_name=None)[source]

Offer a deployed application using a series of endpoints for use by consumers.

@param endpoint: holds the application and endpoint you want to offer @param offer_name: over ride the offer name to help the consumer

create_storage_pool(name, provider_type, **pool_config)[source]

Create or define a storage pool.

Parameters:
  • name (str) – Name to give the storage pool
  • provider_type (str) – Pool provider type
  • **pool_config

    key/value pool configuration pairs

debug_log(no_tail=False, exclude_module=None, include_module=None, include=None, level=None, limit=0, lines=10, replay=False, exclude=None)[source]

Get log messages for this model.

Parameters:
  • no_tail (bool) – Stop after returning existing log messages
  • exclude_module (list) – Do not show log messages for these logging modules
  • include_module (list) – Only show log messages for these logging modules
  • include (list) – Only show log messages for these entities
  • level (str) – Log level to show, valid options are ‘TRACE’, ‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR,
  • limit (int) – Return this many of the most recent (possibly filtered) lines are shown
  • lines (int) – Yield this many of the most recent lines, and keep yielding
  • replay (bool) – Yield the entire log, and keep yielding
  • exclude (list) – Do not show log messages for these entities
coroutine deploy(entity_url, application_name=None, bind=None, budget=None, channel=None, config=None, constraints=None, force=False, num_units=1, plan=None, resources=None, series=None, storage=None, to=None, devices=None, trust=False)[source]

Deploy a new service or bundle.

Parameters:
  • entity_url (str) – Charm or bundle url
  • application_name (str) – Name to give the service
  • bind (dict) – <charm endpoint>:<network space> pairs
  • budget (dict) – <budget name>:<limit> pairs
  • channel (str) – Charm store channel from which to retrieve the charm or bundle, e.g. ‘edge’
  • config (dict) – Charm configuration dictionary
  • constraints (juju.Constraints) – Service constraints
  • force (bool) – Allow charm to be deployed to a machine running an unsupported series
  • num_units (int) – Number of units to deploy
  • plan (str) – Plan under which to deploy charm
  • resources (dict) – <resource name>:<file path> pairs
  • series (str) – Series on which to deploy
  • storage (dict) – Storage constraints TODO how do these look?
  • to

    Placement directive as a string. For example:

    ‘23’ - place on machine 23 ‘lxd:7’ - place in new lxd container on machine 7 ‘24/lxd/3’ - place in container 3 on machine 24

    If None, a new machine is provisioned.

  • trust (bool) – Trust signifies that the charm should be deployed with access to trusted credentials. Hooks run by the charm can access cloud credentials and other trusted access credentials.

TODO:

- support local resources
coroutine destroy()[source]

Terminate all machines and resources for this model. Is already implemented in controller.py.

coroutine destroy_unit(*unit_names)[source]

Destroy units by name.

coroutine destroy_units(*unit_names)

Destroy units by name.

coroutine disconnect()[source]

Shut down the watcher task and close websockets.

enable_ha(num_controllers=0, constraints=None, series=None, to=None)[source]

Ensure sufficient controllers exist to provide redundancy.

Parameters:
  • num_controllers (int) – Number of controllers to make available
  • constraints (juju.Constraints) – Constraints to apply to the controller machines
  • series (str) – Series of the controller machines
  • to (list) –

    Placement directives for controller machines, e.g.:

    '23' - machine 23
    'lxc:7' - new lxc container on machine 7
    '24/lxc/3' - lxc container 3 or machine 24
    

    If None, a new machine is provisioned.

coroutine export_bundle(filename=None)[source]

Exports the current model configuration as a reusable bundle.

coroutine get_action_output(action_uuid, wait=None)[source]

Get the results of an action by ID.

Parameters:
  • action_uuid (str) – Id of the action
  • wait (int) – Time in seconds to wait for action to complete.
Return dict:

Output from action

Raises:

JujuError if invalid action_uuid

coroutine get_action_status(uuid_or_prefix=None, name=None)[source]

Get the status of all actions, filtered by ID, ID prefix, or name.

Parameters:
  • uuid_or_prefix (str) – Filter by action uuid or prefix
  • name (str) – Filter by action name
coroutine get_annotations()[source]

Get annotations on this model.

Return dict:The annotations for this model
get_backup(archive_id)[source]

Download a backup archive file.

Parameters:archive_id (str) – The id of the archive to download
Return str:Path to the archive file
get_backups()[source]

Retrieve metadata for backups in this model.

get_blocks()[source]

List blocks for this model.

get_budget(budget_name)[source]

Get budget usage info.

Parameters:budget_name (str) – Name of budget
get_cached_images(arch=None, kind=None, series=None)[source]

Return a list of cached OS images.

Parameters:
  • arch (str) – Filter by image architecture
  • kind (str) – Filter by image kind, e.g. ‘lxd’
  • series (str) – Filter by image series, e.g. ‘xenial’
coroutine get_config()[source]

Return the configuration settings for this model.

Returns:A dict mapping keys to ConfigValue instances, which have source and value attributes.
coroutine get_constraints()[source]

Return the machine constraints for this model.

Returns:A dict of constraints.
coroutine get_controller()[source]

Return a Controller instance for the currently connected model. :return Controller:

coroutine get_info()[source]

Return a client.ModelInfo object for this Model.

Retrieves latest info for this Model from the api server. The return value is cached on the Model.info attribute so that the valued may be accessed again without another api call, if desired.

This method is called automatically when the Model is connected, resulting in Model.info being initialized without requiring an explicit call to this method.

coroutine get_machines()[source]

Return list of machines in this model.

coroutine get_metrics(*tags)[source]

Retrieve metrics.

Parameters:*tags (str) –

Tags of entities from which to retrieve metrics. No tags retrieves the metrics of all units in the model.

Returns:Dictionary of unit_name:metrics
get_shares()[source]

Return list of all users with access to this model.

get_spaces()[source]

Return list of all known spaces, including associated subnets.

coroutine get_ssh_key(raw_ssh=False)[source]

Return known SSH keys for this model. :param bool raw_ssh: if True, returns the raw ssh key,

else it’s fingerprint
coroutine get_ssh_keys(raw_ssh=False)

Return known SSH keys for this model. :param bool raw_ssh: if True, returns the raw ssh key,

else it’s fingerprint
coroutine get_status(filters=None, utc=False)[source]

Return the status of the model.

Parameters:
  • filters (str) – Optional list of applications, units, or machines to include, which can use wildcards (‘*’).
  • utc (bool) – Display time as UTC in RFC3339 format
get_storage(filesystem=False, volume=False)[source]

Return details of storage instances.

Parameters:
  • filesystem (bool) – Include filesystem storage
  • volume (bool) – Include volume storage
get_storage_pools(names=None, providers=None)[source]

Return list of storage pools.

Parameters:
  • names (list) – Only include pools with these names
  • providers (list) – Only include pools for these providers
get_subnets(space=None, zone=None)[source]

Return list of known subnets.

Parameters:
  • space (str) – Only include subnets in this space
  • zone (str) – Only include subnets in this zone
import_ssh_key(identity)[source]

Add a public SSH key from a trusted indentity source to this model.

Parameters:identity (str) – User identity in the form <lp|gh>:<username>
import_ssh_keys(identity)

Add a public SSH key from a trusted indentity source to this model.

Parameters:identity (str) – User identity in the form <lp|gh>:<username>
info

Return the cached client.ModelInfo object for this Model.

If Model.get_info() has not been called, this will return None.

is_connected()[source]

Reports whether the Model is currently connected.

coroutine list_offers()[source]

Offers list information about applications’ endpoints that have been shared and who is connected.

loop
machines

Return a map of machine-id:Machine for all machines currently in the model.

relations

Return a list of all Relations currently in the model.

remote_applications

Return a map of application-name:Application for all remote applications currently in the model.

remove_backup(backup_id)[source]

Delete a backup.

Parameters:backup_id (str) – The id of the backup to remove
remove_blocks()[source]

Remove all blocks from this model.

remove_cached_images(arch=None, kind=None, series=None)[source]

Remove cached OS images.

Parameters:
  • arch (str) – Architecture of the images to remove
  • kind (str) – Image kind to remove, e.g. ‘lxd’
  • series (str) – Image series to remove, e.g. ‘xenial’
remove_machine(*machine_ids)[source]

Remove a machine from this model.

Parameters:*machine_ids (str) –

Ids of the machines to remove

remove_machines(*machine_ids)

Remove a machine from this model.

Parameters:*machine_ids (str) –

Ids of the machines to remove

coroutine remove_offer(endpoint, force=False)[source]

Remove offer for an application.

Offers will also remove relations to those offers, use force to do so, without an error.

coroutine remove_saas(name)[source]

Removing a consumed (SAAS) application will terminate any relations that application has, potentially leaving any related local applications in a non-functional state.

coroutine remove_ssh_key(user, key)[source]

Remove a public SSH key(s) from this model.

Parameters:
  • key (str) – Full ssh key
  • user (str) – Juju user to which the key is registered
coroutine remove_ssh_keys(user, key)

Remove a public SSH key(s) from this model.

Parameters:
  • key (str) – Full ssh key
  • user (str) – Juju user to which the key is registered
coroutine reset(force=False)[source]

Reset the model to a clean state.

Parameters:force (bool) – Force-terminate machines.

This returns only after the model has reached a clean state. “Clean” means no applications or machines exist in the model.

restore_backup(bootstrap=False, constraints=None, archive=None, backup_id=None, upload_tools=False)[source]

Restore a backup archive to a new controller.

Parameters:
  • bootstrap (bool) – Bootstrap a new state machine
  • constraints (juju.Constraints) – Model constraints
  • archive (str) – Path to backup archive to restore
  • backup_id (str) – Id of backup to restore
  • upload_tools (bool) – Upload tools if bootstrapping a new machine
retry_provisioning()[source]

Retry provisioning for failed machines.

run(command, timeout=None)[source]

Run command on all machines in this model.

Parameters:
  • command (str) – The command to run
  • timeout (int) – Time to wait before command is considered failed
coroutine set_annotations(annotations)[source]

Set annotations on this model.

Parameters:map[string]string (annotations) – the annotations as key/value pairs.
coroutine set_config(config)[source]

Set configuration keys on this model.

Parameters:config (dict) – Mapping of config keys to either string values or ConfigValue instances, as returned by get_config.
coroutine set_constraints(constraints)[source]

Set machine constraints on this model.

Parameters:config (dict) – Mapping of model constraints
sync_tools(all_=False, destination=None, dry_run=False, public=False, source=None, stream=None, version=None)[source]

Copy Juju tools into this model.

Parameters:
  • all (bool) – Copy all versions, not just the latest
  • destination (str) – Path to local destination directory
  • dry_run (bool) – Don’t do the actual copy
  • public (bool) – Tools are for a public cloud, so generate mirrors information
  • source (str) – Path to local source directory
  • stream (str) – Simplestreams stream for which to sync metadata
  • version (str) – Copy a specific major.minor version
tag
unblock(*commands)[source]

Unblock an operation that would alter this model.

Parameters:*commands (str) –

The commands to unblock. Valid values are ‘all-changes’, ‘destroy-model’, ‘remove-object’

units

Return a map of unit-id:Unit for all units currently in the model.

unset_config(*keys)[source]

Unset configuration on this model.

Parameters:*keys (str) –

The keys to unset

upgrade_gui()[source]

Upgrade the Juju GUI for this model.

upgrade_juju(dry_run=False, reset_previous_upgrade=False, upload_tools=False, version=None)[source]

Upgrade Juju on all machines in a model.

Parameters:
  • dry_run (bool) – Don’t do the actual upgrade
  • reset_previous_upgrade (bool) – Clear the previous (incomplete) upgrade status
  • upload_tools (bool) – Upload local version of tools
  • version (str) – Upgrade to a specific version
upload_backup(archive_path)[source]

Store a backup archive remotely in Juju.

Parameters:archive_path (str) – Path to local archive
coroutine wait_for_action(action_id)[source]

Given an action, wait for it to complete.

class juju.model.ModelEntity(entity_id, model, history_index=-1, connected=True)[source]

Bases: object

An object in the Model tree

alive

Returns True if this entity still exists in the underlying model.

current

Return True if this object represents the current state of the entity in the underlying model.

This will be True except when the object represents an entity at a non-latest state in history, e.g. if the object was obtained by calling .previous() on another object.

data

The data dictionary for this entity.

dead

Returns True if this entity no longer exists in the underlying model.

entity_type

A string identifying the entity type of this object, e.g. ‘application’ or ‘unit’, etc.

latest()[source]

Return a copy of this object at its current state in the model.

Returns self if this object is already the latest.

The returned object is always “connected”, i.e. receives live updates from the model.

next()[source]

Return a copy of this object at its next state in history.

Returns None if this object is already the latest.

The returned object is “disconnected”, i.e. does not receive live updates, unless it is current (latest).

on_change(callable_)[source]

Add a change observer to this entity.

on_remove(callable_)[source]

Add a remove observer to this entity.

previous()[source]

Return a copy of this object as was at its previous state in history.

Returns None if this object is new (and therefore has no history).

The returned object is always “disconnected”, i.e. does not receive live updates.

safe_data

The data dictionary for this entity.

If this ModelEntity points to the dead state, it will raise DeadEntityException.

class juju.model.ModelObserver[source]

Bases: object

Base class for creating observers that react to changes in a model.

coroutine on_change(delta, old, new, model)[source]

Generic model-change handler.

This should be overridden in a subclass.

Parameters:
class juju.model.ModelState(model)[source]

Bases: object

Holds the state of the model, including the delta history of all entities in the model.

application_offers

Return a map of application-name:Application for all applications offers currently in the model.

applications

Return a map of application-name:Application for all applications currently in the model.

apply_delta(delta)[source]

Apply delta to our state and return a copy of the affected object as it was before and after the update, e.g.:

old_obj, new_obj = self.apply_delta(delta)

old_obj may be None if the delta is for the creation of a new object, e.g. a new application or unit is deployed.

new_obj will never be None, but may be dead (new_obj.dead == True) if the object was deleted as a result of the delta being applied.

entity_data(entity_type, entity_id, history_index)[source]

Return the data dict for an entity at a specific index of its history.

entity_history(entity_type, entity_id)[source]

Return the history deque for an entity.

get_entity(entity_type, entity_id, history_index=-1, connected=True)[source]

Return an object instance for the given entity_type and id.

By default the object state matches the most recent state from Juju. To get an instance of the object in an older state, pass history_index, an index into the history deque for the entity.

machines

Return a map of machine-id:Machine for all machines currently in the model.

relations

Return a map of relation-id:Relation for all relations currently in the model.

remote_applications

Return a map of application-name:Application for all remote applications currently in the model.

units

Return a map of unit-id:Unit for all units currently in the model.