Variables and Templates
Where variables come from and which one wins, host facts, template filters and CEL expressions.
Variable sources, scope and initialisation priority
Every play creates a separate VariableStore for each host, and the initial variables are written in exactly this order, from low to high (a later row overwrites an earlier one with the same key):
| Priority (low to high) | Source | Scope / notes |
|---|---|---|
| 1 (lowest) | The playbook's top-level vars plus the vars/main.yml of the play's static roles | Global scope; a later role's vars/main.yml is merged into GlobalVars |
| 2 | Inventory host and group variables (TargetVars) | Merged in order: group_vars/all and inventory.all.vars → the member groups' inventory.<group>.vars and group_vars/<group> in alphabetical group order → host_vars/<ip|name> → inline host variables in inventory.<group> → servers[].vars |
| 3 | This host's fact cache from earlier plays | Keys that earlier plays stored in the global fact cache through setup (including gather_facts) and set_fact with an explicit cacheable: true |
| 4 | The current play.vars | Valid only inside the current play |
| 5 | Command line variables (--var-file, -e, --extra-vars) | Applied in the order they appear on the command line, the highest static external injection |
| 6 (reserved connection keys) | The connection variables injected at run time | ip, user, inventory_hostname, port, key_path (when set), password (sensitive), root_password (sensitive) and the read-only hostvars |
Changes made while the play runs (they update the current host's VariableStore in the order they happen):
- the automatic
gather_factsat the start of the play (writesfleetkite_*); - the
setupplugin inside a task (writes or refreshesfleetkite_*); - the
set_factplugin (writes into the currentVariableStoreimmediately; withcacheable: trueit is also persisted into the cross-play fact cache); - any task's
register(writes that task's result object under the given name); - the optional
output_varof theexpectplugin; include_varsandinclude_role(itsvars_from), merged in when the run reaches that task.
Passing values across plays and referencing other hosts
Every play rebuilds the VariableStore
In FleetKite every play rebuilds the VariableStore for each host:
- a
registervariable from an earlier play, an ordinaryset_fact(withoutcacheable: true) and the earlier play'splay.varsdo not carry over into the next play. - only the
fleetkite_*facts gathered bysetupand the variables aset_factexplicitly markedcacheable: truego into the global fact cache, where later plays restore them and expose them throughhostvars.
When hostvars is built and how it is keyed
Before each play starts, the executor takes a snapshot of the global facts:
- Scope: a host's dynamic
set_factinside a play therefore does not appear live in another host'shostvarswithin the same play. Cross-host cooperation needs two plays: play 1 (collect, compute and cache) → play 2 (read the other hosts' data throughhostvars). - Structure: under
hostvars[label]each host has its static target variables (TargetVars, with sensitive fields removed),inventory_hostnameandport, plus afactsobject holding everything cached throughsetuporset_fact cacheable: true. - The index key (
label):- when the host's IP is unique in the
serverslist, it can be reached both ashostvars["192.0.2.10"]and ashostvars["ops@192.0.2.10:22"]; - when several targets share an IP, registered assets use
hostvars["asset:<asset ID>"]and the rest usehostvars["endpoint:user@ip:port"]. IPv6 addresses are bracketed in the endpoint form.
- when the host's IP is unique in the
- Filtering: facts and
hostvarsdrop sensitive fields (such aspassword,secretandtoken), nestedhostvars, Vault ciphertext and any string holding a known sensitive value. Lists keep their positions, with sensitive items replaced bynullor an empty string.
plays:
- name: Play 1 - each database node caches a status marker
hosts: db
tasks:
- name: Read the cluster identifier
type: shell
args:
command: "hostname -s"
register: host_short
changed_when: "false"
- name: Cache the fact for later plays and for hostvars
type: set_fact
args:
db_node_name: "{{ host_short.stdout }}"
cacheable: true
- name: Play 2 - the application hosts read the primary database
hosts: app
tasks:
- name: Show the primary database
type: debug
args:
msg: "Primary DB={{ hostvars['192.0.2.20'].inventory_hostname }}, name={{ hostvars['192.0.2.20'].facts.db_node_name }}, OS={{ hostvars['192.0.2.20'].facts.fleetkite_os_family }}"Built-in variables and the setup fact list
The executor's built-in variables
ip: the IP or address of the host currently connected to (temporarily switched to the delegation target underdelegate_to);user: the SSH login user;port: the SSH port;inventory_hostname: the host's originalipfield in the inventory (unchanged bydelegate_to);key_path: the private key in use, when one is configured;hostvars: the snapshot of other hosts' facts and static variables;item: the element of the current loop iteration; whenloopis a mapping,itemis{ key: "...", value: ... }; withloop_control.indexed_items: true,itembecomes{ index: 0, value: ... }andindexandvalueare also provided directly.
The fleetkite_* variables gathered by setup
| Variable | Example / structure | Description |
|---|---|---|
fleetkite_id | "ubuntu" / "rocky" | The ID from /etc/os-release (and other lower-cased keys such as fleetkite_version_id and fleetkite_pretty_name) |
fleetkite_os_family | "Debian" / "RedHat" / "SUSE" / "Archlinux" / "Alpine" | The normalised distribution family |
fleetkite_architecture | "x86_64" / "aarch64" / "arm64" | From uname -m |
fleetkite_kernel | "6.8.0-45-generic" | From uname -r |
fleetkite_hostname | "web-01" | From hostname |
fleetkite_date_time.iso8601 | "2026-11-27T05:10:00Z" | The target's time |
fleetkite_processor_vcpus | 4 | The number of logical CPU cores |
fleetkite_processor_count | 4 | The number of processor threads |
fleetkite_processor | ["Intel(R) Xeon..."] | The CPU model names |
fleetkite_memtotal_mb / fleetkite_memfree_mb | 4096 / 1820 | Total and available memory in MiB (from /proc/meminfo) |
fleetkite_swaptotal_mb / fleetkite_swapfree_mb | 2048 / 2048 | Total and free swap in MiB |
fleetkite_mounts | [{ device, size_total, size_available, mount }] | The mounted filesystems, with sizes in MiB |
fleetkite_default_ipv4 | { interface, gateway, address } | The default-route interface, gateway and IPv4 address (from ip route) |
The register structure and how loops register
- Flattened:
register: my_resproduces a flat object holdingstatus,msgand every field the plugin returned:- the common fields are
my_res.status("ok"/"changed"/"failed"/"skipped") andmy_res.msg; - the plugin's own fields sit at the first level, for example
my_res.rc,my_res.stdout,my_res.stdout_lines[0],my_res.exists,my_res.status_codeandmy_res.json. Do not add a.dataor.statlayer the way Ansible does.
- the common fields are
- Loop results — once the loop finishes,
my_res.resultsholds the processed items in execution order, each with itsitem, its status and the plugin data. Items whose condition was false are markedskipped: true. An unignored failure ends the loop, and the results already processed are still readable in arescue. The top level keeps the fields of the last execution that actually ran, and adds the summary booleanschangedandfailed.- Read the first item's output with
my_res.results[0].stdout; a delegated or asynchronous loop can read each item's result, for examplejobs.results[0].fleetkite_job_id. - A dry run can produce skipped results, so a task that depends on a file another task produced should check the status first.
- Read the first item's output with
Sensitive variables and the Vault
FleetKite protects credentials in several layers:
- Automatically recognised sensitive keys:
- exact key names:
password,root_password,secret,api_key,token,private_key,auth(plus whateverglobal.sensitive.keywordsadds); - fuzzy substring matches: any variable name containing
password,secret,token,key,auth,credential,passphraseorcookie(plusglobal.sensitive.patterns).
- exact key names:
- Masked output versus safe retrieval:
- the executor's runtime logs, error messages and the
debugplugin's plain template view replace sensitive keys with***MASKED***; reading an exact sensitive key directly returns an empty string. - the
template,expect,transfer_fileandhttpplugins, when they render a target file or a credential header, take the real plaintext out of the Vault through a safe resolver in memory, and immediately register that plaintext with the log redactor so it cannot leak into a log or a diff.
- the executor's runtime logs, error messages and the
- Vault encryption:
fleetkite vault encryptwithFLEETKITE_VAULT_PASSin the environment produces a$FLEETKITEVAULT$...value that is safe to store in a playbook, an inventory orgroup_vars.
Template interpolation, the built-in filters and the gotmpl engine
The default {{ ... }} interpolation and every available filter
FleetKite uses a light interpolation in task arguments and in the template plugin with engine: default. It supports dotted access into nested mappings and array subscripts (such as {{ fleetkite_mounts[0].mount }} and {{ cmd_res.stdout_lines[1] }}), and ships exactly these 14 filters (no other Jinja2 filter is available):
| Filter | Example | Effect |
|---|---|---|
default('val') | {{ http_port | default('8080') }} | Returns 'val' when the variable is undefined or an empty string |
upper / lower | {{ env | upper }} | Upper-cases or lower-cases a string |
trim | {{ res.stdout | trim }} | Removes leading and trailing whitespace |
int / string / bool | {{ port_str | int }}, {{ flag | bool }} | Type conversion (bool understands true/yes/1 and false/no/0) |
replace('old','new') | {{ host | replace('.','-') }} | Replaces every occurrence (note that the single quotes sit directly against the comma) |
dirname / basename | {{ cfg_path | dirname }} | The parent directory or the file name of a path |
first / last | {{ items | first }} | The first or last element of an array |
map(attribute='k') | {{ fleetkite_mounts | map(attribute='mount') }} | Collects one key from a list of objects into an array |
json_query('path') | {{ api_res.json | json_query('items[0].id') }} | Extracts a sub-value from an object or a JSON string by dotted path, [idx] and * |
What interpolation and the filters do not do
- The default interpolation keeps the original text
{{ missing_var }}when it meets an undefined variable without adefault(...)(while external plugins get a strict check that refuses unresolved placeholders). - The
templateplugin withengine: defaultdoes not support{% if %}or{% for %}blocks; a template file that needs conditionals or loops wantsengine: gotmpl.
The gotmpl engine of the template plugin
Setting args.engine: gotmpl (with the optional delimiters: ["[[", "]]"] to avoid clashing with {{ }} inside the file itself) enables Go's standard text/template engine, with missingkey=error on by default so a missing field fails immediately. The built-in helpers are:
upper, lower, trim, quote, basename, dirname, replace, split, join, default, indent, toJson, toYaml.
CEL conditions and status overrides
when, assert.that, failed_when, changed_when and until are all evaluated by the CEL (Common Expression Language) engine:
- Flattened attributes are referenced directly: nested mappings are injected into the environment as dotted paths, so
when: "fleetkite_os_family == 'Debian' && fleetkite_processor_vcpus >= 2"andassert.that: ["probe.status_code == 200", "file_stat.exists"]both work. - Built-in substring sugar: alongside CEL's own functions (
.contains(...),.startsWith(...),.endsWith(...),size(...)), the evaluator rewrites'substr' in varandvar contains 'substr'into a safe substring lookup. failed_whenandchanged_whenget their own context: the current task's not-yet-committed result is available directly, in two forms:- as object properties:
result.rc != 0,"'ERROR' in result.stdout",result.status == 'failed'; - as underscore shorthands:
result_rc != 0,result_msg,result_status,"'FATAL' in result_stdout".
- as object properties:
untilvariables: whenuntilis used without aregister, the executor registers the result under the default nameresult; the condition may then usehealth.status_code == 200or reach the top-level keys of the current attempt directly (such asrc == 0orexists).
Next steps
- Built-in plugins — the full parameter reference for every
type - Security practices — how sensitive data is handled and where the transfer boundaries are