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?
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 thestd.time()function to turn it back into a validTIMEtype.See https://varnish-cache.org/docs/7.4/reference/vmod_std.html#std-time to learn more about the
stdVMOD and itsstd.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_varthat 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.