How to access a resource from your charm

See also: Model (ops.model.Model)

In order to make use of file resources in a charm, the Charmed Operator Framework provides a helper method to fetch the path of a file resource. Consider this simple resource definition:

    type: file
    filename: somefile.txt
    description: test resource

In the charm code, we can now use Model.resources.fetch(<resource_name>) to get the path to the resource, then manipulate it as we need:

# ...
import logging
from ops.model import ModelError, BlockedStatus, ErrorStatus
# ...
logger = logging.getLogger(__name__)

def _on_config_changed(self, event):
    # Get the path to the file resource named 'my-resource'
        resource_path = self.model.resources.fetch("my-resource")
    except ModelError as e:
        self.unit.status = BlockedStatus(
            "Something went wrong when claiming resource 'my-resource; "
            "run `juju debug-log` for more info'"
       # might actually be worth it to just reraise this exception and let the charm error out;
       # depends on whether we can recover from this.
    except NameError as e:
        self.unit.status = BlockedStatus(
            "Resource 'my-resource' not found; "
            "did you forget to declare it in metadata.yaml?"

    # Open the file and read it
    with open(resource_path, "r") as f:
        content =
    # do something

The fetch() method will raise a ModelError if the resource does not exist, and returns a Python Path object to the resource if it does.

Note: During development, it may be useful to specify the resource at deploy time to facilitate faster testing without the need to publish a new charm/resource in between minor fixes. In the below snippet, we create a simple file with some text content, and pass it to the Juju controller to use in place of any published my-resource resource:

echo "TEST" > /tmp/somefile.txt
charmcraft pack
juju deploy ./my-charm.charm --resource my-resource=/tmp/somefile.txt

Last updated 14 days ago.