How to create custom local variables in Varnish?

87 Views Asked by At

I'm using Varnish 7.4 OSS with no extra VMODs installed and for readability I'd like to store a computed value in a local variable, that I'll use a few lines later, within the same vcl_* step.

But I didn't find a way to do that in the docs.

I tried:

  • set v1 = "hello";
  • new v1 = "hello2";
  • STRING v1;

But all gave an error.

The only variables I was able to add were HTTP headers, like set req.http.v1 = "hello", but of course that stopped working as soon as I needed to store a TIME value.

How do I do it?

1

There are 1 best solutions below

2
Thijs Feryn On

VCL has no native concept of variables. Therefor headers are often (ab)used instead: storing values in headers and reading those header values later. Either in the same subroutine or in another.

Using headers and std.time()

If you want to store a time value, you can assign the string value via the set req.http.x-some-time = "2024-07-08T08:49:37" syntax and use the std.time() function to turn it back into a valid TIME type.

See https://varnish-cache.org/docs/7.4/reference/vmod_std.html#std-time to learn more about the std VMOD and its std.time() function.

Don't forget to add import std; to your VCL file to make the namespace available to your VCL code.

Using vmod_var

There is an open source VMOD called vmod_var that offers variable support in Varnish. You can download it from https://github.com/varnish/varnish-modules. You'll have to compile it from source though.

See https://github.com/varnish/varnish-modules/blob/master/src/vmod_var.vcc for the API and some code examples.

Eventually we will provide packages for these VMODs on https://packagecloud.io/varnishcache/, but for now compiling the VMODs from source is still required.