This document details how to use
charmcraft to interact with libraries.
Finding and using libraries
If the charm you’re writing needs to interact with another application, you can check if the relevant application charm provides a library that could aid that interaction. The easiest way to see this from the command line is using the
charmcraft list-lib command, which will query Charmhub and show which libraries are published for the specified charm, along with API/patch versions:
$ charmcraft list-lib demo Library name API Patch demo 0 1
The listing will not show older API versions, ensuring that new users always start with the latest version. Once you have discovered a library you want to use, you need to fetch it from Charmhub before it can be imported by your charm code. This is done using the
charmcraft fetch-lib command:
$ charmcraft fetch-lib charms.demo.v0.demo Library charms.demo.v0.demo version 0.1 downloaded.
That command will download the library, creating the required directory layout in your charm directory:
$ ls -l lib/charms/demo/v0/demo.py -rw-rw-r-- 1 user user 1061 Apr 06 15:24 lib/charms/demo/v0/demo.py
This file is now part of our charm’s project; it will be included with our charm (and therefore distributed with it) when the charm is packaged and published with
charmcraft. Using the library is now trivial, it can just be imported in your charm’s code (note that the charm automatically has the
lib directory as part of the Python import paths).
from charms.demo.v0 import demo
To update the version of the library you are consuming, you can simply run the
charmcraft fetch-lib command again - the latest version will be fetched if there is an update available:
$ charmcraft fetch-lib charms.demo.v0.demo Library charms.demo.v0.demo was already up to date in version 0.1.
Charm libraries should always be initialised using the
charmcraft tool. Suppose we are creating a library as part of a charm named
# Initialise a charm library named 'demo' $ charmcraft create-lib demo
Before creating a library, you must first register ownership of your charm’s name. This is covered in the Publishing section.
This will create a file at
$CHARMDIR/lib/charms/demo/v0/demo.py. Charm libraries are always located according to the pattern:
$CHARMDIR/lib/charms/<charm_name>/v<API>/<library_name>.py. Developers can import the library from within their charm code using its fully-qualified path:
Once your library is complete, publishing it is simple - a single command will both publish the library to Charmhub, and make it available for consumption by other charm authors:
$ charmcraft publish-lib charms.demo.v0.demo Library charms.demo.v0.demo sent to the store with version 0.1
Last updated 21 days ago.