Crate tera_rand

source ·
Expand description

tera-rand

A crate of random data generation functions for the Tera template engine.

For a CLI tool implementation using this crate, see tera-rand-cli.

Example usage

Import the function you would like to use, and register it with Tera::register_function. Your Tera templates may then use that function:

use tera::{Context, Tera};
use tera_rand::random_string;
use tera_rand::random_ipv4_cidr;

let mut tera: Tera = Tera::default();
tera.register_function("random_string", random_string);
tera.register_function("random_ipv4_cidr", random_ipv4_cidr);

let context: Context = Context::new();
// generate a random String and a random IPv4 CIDR address in a JSON template string
let rendered_json: String = tera
    .render_str(
        r#"{"hostname": "{{ random_string() }}", "subnet": "{{ random_ipv4_cidr() }}"}"#,
        &context
    )
    .unwrap();

Tera takes the template String, inserts random values wherever the functions were called, and spits out a rendered String, which in this case might look like this:

{"hostname": "VtNCOgwH", "subnet": "196.119.240.0/23"}

Some functions provide customization parameters. For example, random_string provides a length parameter to specify the length of the generated String, and random_ipv4_cidr provides length_start and length_end parameters to limit the possible prefix lengths. The template in the above example could be modified to this:

{
    "hostname": "{{ random_string(length=12) }}",
    "subnet": "{{ random_ipv4_cidr(length_start=28, length_end=30) }}"
}

and the generated JSON could look like this:

{
    "hostname": "YCHcsV6bRkVW",
    "subnet": "171.150.226.224/29"
}

Functions

  • A Tera function to sample a specific value from a line-delimited file of strings. The filepath should be passed in as an argument to the path parameter. The 0-indexed line number should be passed in as an argument to the line_num parameter.
  • A Tera function to generate a random boolean.
  • A Tera function to generate a random char.
  • A Tera function to generate a random 32-bit float.
  • A Tera function to generate a random 64-bit float.
  • A Tera function to sample a random value from a line-delimited file of strings. The filepath should be passed in as an argument to the path parameter.
  • A Tera function to generate a random signed 32-bit integer.
  • A Tera function to generate a random signed 64-bit integer.
  • A Tera function to generate a random IPv4 address.
  • A Tera function to generate a random IPv4 CIDR address.
  • A Tera function to generate a random IPv6 address.
  • A Tera function to generate a random IPv6 CIDR address.
  • A Tera function to generate a random String.
  • A Tera function to generate a random unsigned 32-bit integer.
  • A Tera function to generate a random unsigned 64-bit integer.
  • A Tera function to generate a random UUIDv4.