Skip to Content
FleetKiteFleetKite

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)SourceScope / notes
1 (lowest)The playbook's top-level vars plus the vars/main.yml of the play's static rolesGlobal scope; a later role's vars/main.yml is merged into GlobalVars
2Inventory 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
3This host's fact cache from earlier playsKeys that earlier plays stored in the global fact cache through setup (including gather_facts) and set_fact with an explicit cacheable: true
4The current play.varsValid only inside the current play
5Command 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 timeip, 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):

  1. the automatic gather_facts at the start of the play (writes fleetkite_*);
  2. the setup plugin inside a task (writes or refreshes fleetkite_*);
  3. the set_fact plugin (writes into the current VariableStore immediately; with cacheable: true it is also persisted into the cross-play fact cache);
  4. any task's register (writes that task's result object under the given name);
  5. the optional output_var of the expect plugin;
  6. include_vars and include_role (its vars_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 register variable from an earlier play, an ordinary set_fact (without cacheable: true) and the earlier play's play.vars do not carry over into the next play.
  • only the fleetkite_* facts gathered by setup and the variables a set_fact explicitly marked cacheable: true go into the global fact cache, where later plays restore them and expose them through hostvars.

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_fact inside a play therefore does not appear live in another host's hostvars within the same play. Cross-host cooperation needs two plays: play 1 (collect, compute and cache) → play 2 (read the other hosts' data through hostvars).
  • Structure: under hostvars[label] each host has its static target variables (TargetVars, with sensitive fields removed), inventory_hostname and port, plus a facts object holding everything cached through setup or set_fact cacheable: true.
  • The index key (label):
    • when the host's IP is unique in the servers list, it can be reached both as hostvars["192.0.2.10"] and as hostvars["ops@192.0.2.10:22"];
    • when several targets share an IP, registered assets use hostvars["asset:<asset ID>"] and the rest use hostvars["endpoint:user@ip:port"]. IPv6 addresses are bracketed in the endpoint form.
  • Filtering: facts and hostvars drop sensitive fields (such as password, secret and token), nested hostvars, Vault ciphertext and any string holding a known sensitive value. Lists keep their positions, with sensitive items replaced by null or 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 under delegate_to);
  • user: the SSH login user;
  • port: the SSH port;
  • inventory_hostname: the host's original ip field in the inventory (unchanged by delegate_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; when loop is a mapping, item is { key: "...", value: ... }; with loop_control.indexed_items: true, item becomes { index: 0, value: ... } and index and value are also provided directly.

The fleetkite_* variables gathered by setup

VariableExample / structureDescription
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_vcpus4The number of logical CPU cores
fleetkite_processor_count4The number of processor threads
fleetkite_processor["Intel(R) Xeon..."]The CPU model names
fleetkite_memtotal_mb / fleetkite_memfree_mb4096 / 1820Total and available memory in MiB (from /proc/meminfo)
fleetkite_swaptotal_mb / fleetkite_swapfree_mb2048 / 2048Total 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

  1. Flattened: register: my_res produces a flat object holding status, msg and every field the plugin returned:
    • the common fields are my_res.status ("ok" / "changed" / "failed" / "skipped") and my_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_code and my_res.json. Do not add a .data or .stat layer the way Ansible does.
  2. Loop results — once the loop finishes, my_res.results holds the processed items in execution order, each with its item, its status and the plugin data. Items whose condition was false are marked skipped: true. An unignored failure ends the loop, and the results already processed are still readable in a rescue. The top level keeps the fields of the last execution that actually ran, and adds the summary booleans changed and failed.
    • Read the first item's output with my_res.results[0].stdout; a delegated or asynchronous loop can read each item's result, for example jobs.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.

Sensitive variables and the Vault

FleetKite protects credentials in several layers:

  1. Automatically recognised sensitive keys:
    • exact key names: password, root_password, secret, api_key, token, private_key, auth (plus whatever global.sensitive.keywords adds);
    • fuzzy substring matches: any variable name containing password, secret, token, key, auth, credential, passphrase or cookie (plus global.sensitive.patterns).
  2. Masked output versus safe retrieval:
    • the executor's runtime logs, error messages and the debug plugin's plain template view replace sensitive keys with ***MASKED***; reading an exact sensitive key directly returns an empty string.
    • the template, expect, transfer_file and http plugins, 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.
  3. Vault encryption: fleetkite vault encrypt with FLEETKITE_VAULT_PASS in the environment produces a $FLEETKITEVAULT$... value that is safe to store in a playbook, an inventory or group_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):

FilterExampleEffect
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 a default(...) (while external plugins get a strict check that refuses unresolved placeholders).
  • The template plugin with engine: default does not support {% if %} or {% for %} blocks; a template file that needs conditionals or loops wants engine: 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" and assert.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 var and var contains 'substr' into a safe substring lookup.
  • failed_when and changed_when get their own context: the current task's not-yet-committed result is available directly, in two forms:
    1. as object properties: result.rc != 0, "'ERROR' in result.stdout", result.status == 'failed';
    2. as underscore shorthands: result_rc != 0, result_msg, result_status, "'FATAL' in result_stdout".
  • until variables: when until is used without a register, the executor registers the result under the default name result; the condition may then use health.status_code == 200 or reach the top-level keys of the current attempt directly (such as rc == 0 or exists).

Next steps

On this page