Skip to content

Core Tasks

Core Tasks

Tasks that are a core part of uPlaybook.

Argument

A playbook argument, this class is used to describe the details of an argument/option.

Use this to provide details about arguments or options that can be used with a playbook. These get turned into command-line arguments that can be described with "--help". This is used in combination with the core.playbook_args() task.

Names that include "_" (underscore) will be converted to "-" (hyphen) for the command line argument.

Parameters:

Name Type Description Default
name str

The name of the argument, this will determine the "--name" of the command-line flag and the variable the value is stored in (str).

required
description Optional[str]

Detailed information on the argument for use in "--help" output. (str, optional)

None
type str

The type of the argument: str, bool, int, password (default=str)

'str'
default Optional[object]

A default value for the argument. Arguments without a default must be specified in the command-line. If default is specified, a command-line option with "--name" will be available.

None

Examples:

core.playbook_args(options=[
        core.Argument(name="user"),
        core.Argument(name="hostname", default=None)
        core.Argument(name="enable", type="bool", default=True)
        ])
core.debug(msg="Arguments: user={{ARGS.user}}  hostname={{ARGS.hostname}} enable={{ARGS.enable}}")

#  Run with "up2 playbookname --hostname=localhost --no-enable username

IgnoreFailure

A context-manager to ignore failures in wrapped tasks.

Example:

with core.IgnoreFailures():
    core.run("false")
    if not core.mkdir("/root/failure"):
        print("You are not root")

Item

Bases: dict

An (ansible-like) item for processing in a playbook (a file, directory, user...)

A typical use case of an Item is for looping over many files and setting them up, or setting up many filesystem objects in a playbook. Additionally, if used in a "with:" statement, it will place the attributes into the current Jinja2 namespace.

This can act as a dictionary (x['attr'] access), SimpleNamespace (x.attr), and also is a context manager. In the context manager case, it forklifts the attributes up into the Jinja2 context.

Examples:

fs.builder(
        defaults=Item(owner="root", mode="a=rX"),
        items=[
            Item(path="foo"),
            Item(path="bar"),
            ])

for item in [
        Item(path="foo"),
        Item(path="bar"),
        Item(path="baz"),
        ]:
    fs.builder(path="{{item.dst}}")

for item in [
        Item(path="foo", action="directory", owner="nobody"),
        Item(path="bar", action="exists"),
        Item(path="/etc/apache2/sites-enabled/foo", notify=restart_apache),
        ]:
    fs.builder(**item)

with Item(path="foo", action="directory", owner="nobody") as item:
    #  Can access as "dst" as well as "item.dst"
    fs.exists(path="{{dst}}")
    fs.chown(path="{{dst}}", owner="{{owner}}")

with Item(path="foo", action="directory", owner="nobody"):
    fs.exists(path="{{dst}}")

become(user)

Switch to running as another user in a playbook.

If used as a context manager, you are switched back to the original user after the context.

Parameters:

Name Type Description Default
user Union[int, TemplateStr]

User name or UID of user to switch to.

required

Examples:

core.become(user="nobody")

with core.become(user="backup"):
    #  to tasks as backup user
    fs.mkfile(path="/tmp/backupfile")
#  now you are back to the previous user

debug(msg=None, var=None)

Display informational message.

Print a message or pretty-print a variable.

Parameters:

Name Type Description Default
msg Optional[TemplateStr]

Message to display. (optional, templateable).

None
var Optional[object]

Object to pretty-print (optional, templateable).

None

Examples:

core.debug(msg="Directory already exists, exiting")
core.debug(var=ret_value)

exit(returncode=0, msg='')

End a playbook run.

Parameters:

Name Type Description Default
returncode int

Exit code for process, 0 is success, 1-255 are failure (int, default=0).

0
msg Union[TemplateStr, str]

Message to display (str, templatable, default "").

''

Examples:

core.exit()
core.exit(returncode=1)
core.exit(msg="Unable to download file", returncode=1)

fail(msg)

Abort a playbook run.

Parameters:

Name Type Description Default
msg TemplateStr

Message to display with failure (str, templateable).

required

Examples:

core.fail(msg="Unable to download file")

flush_handlers()

Run any registred handlers.

Examples:

core.flush_handlers()

get_url(url, path, skip_if_path_exists=True)

Access another playbook from an existing playbook.

Parameters:

Name Type Description Default
url TemplateStr

URL to download.

required
path TemplateStr

Location to write file.

required
skip_if_path_exists bool

If path already exists, do not download again.

True

Examples:

core.get_url(url="https://google.com")

grep(path, search, regex=True, ignore_failure=True)

Look for search in the file path

Parameters:

Name Type Description Default
path TemplateStr

File location to look for a match in. (templateable)

required
search TemplateStr

The string (or regex) to look for. (templateable)

required
regex bool

Do a regex search, if False do a simple string search. (bool, default=True)

True
ignore_failure bool

If True, do not treat file absence as a fatal failure. (optional, bool, default=True)

True

Examples:

if core.grep(path="/tmp/foo", search="secret=xyzzy"):
    #  code for when the string is found.

include(playbook, hoist_vars=True)

Access another playbook from an existing playbook.

Parameters:

Name Type Description Default
playbook TemplateStr

Playbook to include. (templateable)

required
hoist_vars bool

If True (the default), variables set in the playbook are "hoisted" up into the main playbook.

True

Examples:

core.include(playbook="set_vars.pb")

lookup(var)

Looks up var in the "up context" and returns the value.

This would typically be similar to Jinja2 rendering "{{var}}", but it does not go through "." traversing, so var must be a top level name.

Examples:

print(core.lookup('name'))

notify(handler)

Add a notify handler to be called later.

Parameters:

Name Type Description Default
handler Union[Callable, List]

A function, or list of functions, that takes no arguments, which is called at a later time. (callable or list)

required

Examples:

core.notify(lambda: core.run(command="systemctl restart apache2"))
core.notify(lambda: fs.remove("tmpdir", recursive=True))
core.notify([handler1, handler2])

playbook_args(options)

Specify arguments for a playbook.

Optionally, a playbook may specify that it needs arguments. If defined, this will create an argument parser and command-line arguemnts and options.

Examples:

core.playbook_args(options=[
        core.Argument(name="is_owner", default=False, type="bool"),
        core.Argument(name="user"),
        core.Argument(name="hostname", default="localhost")
        ])
core.debug(msg="Arguments: user={{playbook_args.user}}  hostname={{playbook_args.hostname}}")
core.debug(msg="Arguments: is_owner={{playbook_args.is_owner}}")
#  run examples:
#    up playbook.pb my_username
#    up playbook.pb --is-owner my_username
#    up playbook.pb --no-is-owner my_username my_hostname

print(msg)

uPlaybook print helper, like python print() but does jinja templating.

Parameters:

Name Type Description Default
msg TemplateStr

Message to print. (templateable)

required

Examples:

core.print("Arguments: {{playbook_arguments}}")

render(s)

Render a string as a jinja2 template and return the value

Parameters:

Name Type Description Default
s TemplateStr

Template to render. (templateable).

required

Returns:

Type Description
str

Rendered template as a string.

Examples:

core.render(s="Value of foo: {{foo}}")

require(user)

Verify we are running as the specified user.

Parameters:

Name Type Description Default
user Union[int, TemplateStr]

User name or UID of user to verify. (int or str, templateable)

required

Examples:

core.require(user="nobody")

run(command, shell=True, ignore_failure=False, change=True, creates=None)

Run a command. Stdout is returned as output in the return object. Stderr and return code are stored in extra in return object.

Parameters:

Name Type Description Default
command TemplateStr

Command to run (templateable).

required
shell bool

If False, run command without a shell. Safer. Default is True: allows shell processing of command for things like output redirection, wildcard expansion, pipelines, etc. (optional, bool)

True
ignore_failure bool

If True, do not treat non-0 return code as a fatal failure. This allows testing of return code within playbook. (optional, bool)

False
change bool

By default, all shell commands are assumed to have caused a change to the system and will trigger notifications. If False, this command is treated as not changing the system. (optional, bool)

True
creates Optional[TemplateStr]

If specified, if the path it specifies exists, consider the command to have already been run and skip future runes.

None

Extra Data:

stderr: Captured stderr output.
returncode: The return code of the command.

Examples:

core.run(command="systemctl restart sshd")
core.run(command="rm *.foo", shell=False)   #  removes literal file "*.foo"

r = core.run(command="date", change=False)
print(f"Current date/time: {{r.output}}")
print(f"Return code: {{r.extra.returncode}}")

if core.run(command="grep -q ^user: /etc/passwd", ignore_failure=True, change=False):
    print("User exists")