Good morning programmers, I'm trying to create random variables on nginx, (I have OpenResty nginx+lua). Here is an example of a static variable:
set $teste 123;
So is it possible to turn this static variable random?
You need to provide random seed, otherwise you'll get the same values each time the server is restarted.
There I use resty.random.bytes
(that internally uses RAND_pseudo_bytes or RAND_bytes from OpenSSL) to provide cryptographically strong pseudo-random seed on nginx worker start.
UPD: You should use resty_random.bytes(n, true)
for really cryptographically strong pseudo-random value. If the second argument is true
, RAND_bytes
will be used instead of RAND_pseudo_byte
. But in this case you'll have to deal with possible exhaustion of the entropy pool. That is, resty_random.bytes(n, true)
could return nil
if there is no enough randomness to ensure an unpredictable byte sequence.
http {
init_worker_by_lua_block {
local resty_random = require('resty.random')
-- use random byte (0..255 int) as a seed
local seed = string.byte(resty_random.bytes(1))
math.randomseed(seed)
}
server {
listen 8888;
location = / {
set_by_lua_block $random {
return math.random(1, 100)
}
echo "random number: $random";
}
}
}
If you're using openresty, you can do it with the help of lua, for example (generating 3 digits):
set_by_lua_block $teste { return string.format('%03d', math.random(1, 999)) }