juju.model

Summary

BundleHandler

Handle bundles by using the API to translate bundle YAML into a plan of steps and then dispatching each of those using the API.

Methods:

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:

get_charm_series
Inspects the charm directory at path and returns a default series from its metadata.yaml (the first item in the ‘series’ list).

Reference

class juju.model.BundleHandler(model)[source]

Bases: object

Handle bundles by using the API to translate bundle YAML into a plan of steps and then dispatching each of those using the API.

coroutine addCharm(charm, series)[source]
Parameters:
  • string (series) – Charm holds the URL of the charm to be added.
  • string – Series holds the series of the charm to be added if the charm default is not sufficient.
coroutine addMachines(params=None)[source]
Parameters:dict (params) –

Dictionary specifying the machine to add. All keys are optional. Keys include:

series: string specifying the machine OS series.

constraints: string holding machine constraints, if any. We’ll
parse this into the json friendly dict that the juju api expects.
container_type: string holding the type of the container (for
instance “”lxd” or kvm”). It is not specified for top level machines.
parent_id: string holding a placeholder pointing to another
machine change or to a unit change. This value is only specified in the case this machine is a container, in which case also ContainerType is set.
coroutine addRelation(endpoint1, endpoint2)[source]
Parameters:
  • string (endpoint2) –
  • string – Endpoint1 and Endpoint2 hold relation endpoints in the “application:interface” form, where the application is always a placeholder pointing to an application change, and the interface is optional. Examples are “$deploy-42:web” or just “$deploy-42”.
coroutine addUnit(application, to)[source]
Parameters:
  • string (to) – Application holds the application placeholder name for which a unit is added.
  • string – To holds the optional location where to add the unit, as a placeholder pointing to another unit change or to a machine change.
applications
coroutine deploy(charm, series, application, options, constraints, storage, endpoint_bindings, resources)[source]
Parameters:
  • string (constraints) – Charm holds the URL of the charm to be used to deploy this application.
  • string – Series holds the series of the application to be deployed if the charm default is not sufficient.
  • string – Application holds the application name.
  • map[string]interface{} (options) – Options holds application options.
  • string – Constraints holds the optional application constraints.
  • map[string]string (endpoint_bindings) – Storage holds the optional storage constraints.
  • map[string]string – EndpointBindings holds the optional endpoint bindings
  • map[string]int (resources) – Resources identifies the revision to use for each resource of the application’s charm.
coroutine execute_plan()[source]
coroutine expose(application)[source]
Parameters:string (application) – Application holds the placeholder name of the application that must be exposed.
coroutine fetch_plan(entity_id)[source]
resolve(reference)[source]
coroutine setAnnotations(id_, entity_type, annotations)[source]
Parameters:
  • string (id) – Id is the placeholder for the application or machine change corresponding to the entity to be annotated.
  • EntityType (entity_type) – EntityType holds the type of the entity, “application” or “machine”.
  • map[string]string (annotations) – Annotations holds the annotations as key/value pairs.
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)[source]

Bases: object

Async wrapper around theblues.charmstore.CharmStore

class juju.model.Model(loop=None, max_frame_size=’default_frame_size’)[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' - manually provisions a machine with ssh
    '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.

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.

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

Connect to an arbitrary Juju model.

args and kw are passed through to Connection.connect()

coroutine connect_current()[source]

Connect to the current Juju model.

coroutine connect_model(model_name)[source]

Connect to a specific Juju model by name.

Parameters:model_name – Format [controller:][user/]model
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

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

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.

get_action_output(action_uuid, wait=-1)[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
get_action_status(uuid_or_prefix=None, name=None)[source]

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

Parameters:
  • uuid_or_prefix (str) – Filter by action uuid or prefix
  • name (str) – Filter by action name
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’
get_config()[source]

Return the configuration settings for this model.

get_constraints()[source]

Return the machine constraints for this model.

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
coroutine grant(username, acl=’read’)[source]

Grant a user access to this model.

Parameters:
  • username (str) – Username
  • acl (str) – Access control (‘read’ or ‘write’)
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>
machines

Return a map of machine-id:Machine for all machines 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_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.

coroutine revoke(username)[source]

Revoke a user’s access to this model.

Parameters:username (str) – Username to revoke
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
set_config(**config)[source]

Set configuration keys on this model.

Parameters:**config – Config key/values
set_constraints(constraints)[source]

Set machine constraints on this model.

:param juju.Constraints constraints: Machine 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
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.

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.

units

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

juju.model.get_charm_series(path)[source]

Inspects the charm directory at path and returns a default series from its metadata.yaml (the first item in the ‘series’ list).

Returns None if no series can be determined.