How to find and use a charm library

See also:

This document shows how to take advantage of existing charm libraries.


Discover an existing charm library

You’ve come to the conclusion that you’d like a charm library. The first thing to do is check if there is already an existing one that you can use. For example, if the charm you’re writing needs to interact with another service, you should check if that service provides any library that would help in that interaction.

The easiest way to find an existing library for a given charm is via charmcraft list-lib, as shown below. This will query Charmhub and show which libraries are published for the specified charm, along with API/patch versions.

jdoe@machine:/home/jane/autoblog$ charmcraft list-lib blogsystem
Library name    API    Patch
superlib        1      0

The listing will not show older API versions; this ensures that new users always start with the latest version.

Another good way to search for libraries is to explore the charm collection on Charmhub.

Fetch a charm library

You’ve found a library that suits you. Now, you need to fetch it. To do this, execute charmcraft fetch-lib followed by the full library path:

$ charmcraft fetch-lib charms.demo.v0.demo
Library charms.demo.v0.demo version 0.1 downloaded.

Charm libraries are always located according to the pattern: $CHARMDIR/lib/charms/<charm_name>/v<API>/<library_name>.py. See The location of a charm library inside a charm.

This command will download the library, creating the required directory layout in your charm directory:

$ ls -l lib/charms/demo/v0/
-rw-rw-r-- 1 user user 1061 Apr 06 15:24 lib/charms/demo/v0/

This file is now part of your charm’s project. It will be packed inside your charm and distributed with it when the charm is packaged and published with charmcraft.

Import a charm library

You’ve fetched a library—it’s now time to use it! To use the library, you need to import it in your charm’s code, as shown below. (Note that the charm automatically has the lib directory as part of the Python import paths.)

from charms.demo.v0 import demo

Update a charm library

To update the version of the library you are consuming, run the charmcraft fetch-lib command again—if there is an update available, this will fetch it:

$ charmcraft fetch-lib charms.demo.v0.demo
Library charms.demo.v0.demo was already up to date in version 0.1.

Last updated 7 months ago. Help improve this document in the forum.