Resources Plugins Tutorial
Resources are defined using plugins, every plugin defines a single resource that can receive actions (build, test, publish and deploy), here we will learn how to create a new resource by writing a plugin for it.
Resource class
The resource class should be called like this <ResourceKind>Resource and must inherit from Resource base class,
this class must implement these methods:
init: This method is called first when the resource is being initialized, we get the resource’s file as an argument and first we call constructor for the base class with this code:
super().__init__(file)
This call will setup the resource for us by reading the file, parsing yaml into an attribute called spec, it raises errors if file does not exist, is not valid yaml file, has no metadata, kind or name and it sets some private attributes to be used later by the public methods.
action: Theis method implemenst the basic actions for the resource, it takes action name, state, and env as arguments and do its work, it may raise one of these exceptions in case of errors: errors.ResourceBuildError, errors.ResourceTestError, errors.ResourcePublishError and errors.ResourceDeployError and if there are no errors, it returns a dictionary as follows: the artifacts key of the dictionary will be a list of artifact objects created using the create_artifact method in base class, it might also have the globals key which is a dictionary of key value pairs that are stored as output from the resource and can be used in other resources any other keys are stored in state without any change or special meaning.
The create_artifact method takes these arguments: id, action, env, hash, kind and data. kind can be either of file, url or text, in case of a file then data is the file’s path.
re_action: This method take action, state and env as arguments and is used to implement custom logic for re-running an action on the resource, it returns True if the action must be re-run.
All of these methods must be decorated with hash.resources.hookimpl function.
Here are some helper methods in resource Base class
getFile: returns an absolute path to the resource’s file.
getPath: returns an absolute path to the resource’s code.
getSpec: returns the value of a spec, it takes key as argument and an optioanl default value if the key is not found.
raise_resource_error: takes action name as argument and an error object as second argument and it raises the right error according to the action’s name.
execute: Takes command to execute as a string and the path to execute the command, it then executes the command using subprocess module and returns the subprocess.CompletedProcess object.