A resource is an additional or some additional content that a charm can make use of, or may require to run. This can be especially useful where you need to include large blobs (perhaps a database, media file or otherwise) that may not need to be updated with the same cadence as the charm or workload itself. By keeping resources separate, you can control the lifecycle of these elements more carefully, and in some situations avoid the need for repeatedly downloading large files from Charmhub during routine upgrades/maintenance.
Resources are defined in a charm’s
metadata.yaml and are therefore intrinsically linked to a charm. Because of this, there is no need to register them separately in Charmhub. Other charms may have resources with the same name, but this is not a problem; references to resources always contain the charm name and resource name.
resources is defined as a top-level YAML map, where each key in the map is the name of a resource, that can map to the following fields:
||Type of the resource. Supported values are
||Description of the resource|
||Name of the file resource|
An example resource definition:
# ... resources: someresource: type: file filename: superdb.bin description: the DB with needed info app-image: type: oci-image description: OCI image for app # ...
Kubernetes charms must declare an
oci-image resource for each container they define in the
Accessing resources from the charm
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:
resources: my-resource: 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:
# ... from ops.model import ModelError, BlockedStatus # ... def _on_config_changed(self, event): # Get the path to the file resource named 'my-resource' try: resource_path = self.model.resources.fetch("my-resource") except ModelError: self.unit.status = BlockedStatus("Missing 'my-resource' resource") return # Open the file and read it with open(resource_path, "r") as f: content = f.read() # do something
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
$ echo "TEST" > /tmp/somefile.txt
$ charmcraft pack
$ juju deploy ./my-charm.charm --resource my-resource=/tmp/somefile.txt
Last updated 6 days ago.