如何在supervisord配置中引用现有环境变量设置新环境变量?

3 投票
1 回答
1925 浏览
提问于 2025-04-18 09:54

我正在尝试在我的 supervisord 配置中设置一个环境变量,想用一个已经存在的环境变量的值。这个已有的变量是 REDIS_PORT_6379_TCP_ADDR(来自一个 Docker 连接的容器);它的值是一个 IP 地址(比如 172.17.0.5)。这是我第一次简单的尝试:

[program:sidekiq]
user=web
directory=/var/www
environment=REDIS_URL=redis://$REDIS_PORT_6379_TCP_ADDR:6379/0
command=bundle exec sidekiq -c 50
redirect_stderr=true
autorestart=true

但是这个完全不行,因为 supervisord 不能解析它:

$ supervisord -c /etc/supervisor/supervisord.conf -n
Error: Unexpected end of key/value pairs
For help, use /usr/bin/supervisord -h

然后我试着把环境部分用引号括起来:

environment=REDIS_URL="redis://$REDIS_PORT_6379_TCP_ADDR:6379/0"

结果也不行,因为变量在传给我的程序之前没有被替换:

2014-06-16T03:08:35Z 240 TID-oqy09ga9c WARN: the scheme redis does not accept registry part: $REDIS_PORT_6379_TCP_ADDR:6379 (or bad hostname?)

接着,根据 这个回答,我尝试使用 %(ENV) 这种语法:

environment=REDIS_URL="redis://%(ENV_REDIS_PORT_6379_TCP_ADDR):6379/0"

结果又一次不能解析:

$ supervisord -c /etc/supervisor/supervisord.conf -n                              
Error: Format string 'REDIS_URL="redis://%(ENV_REDIS_PORT_6379_TCP_ADDR):6379/0"' for 'environment' is badly formatted
For help, use /usr/bin/supervisord -h

如果我去掉双引号,结果也是一样:

$ supervisord -c /etc/supervisor/supervisord.conf -n
Error: Format string 'REDIS_URL=redis://%(ENV_REDIS_PORT_6379_TCP_ADDR):6379/0' for 'environment' is badly formatted
For help, use /usr/bin/supervisord -h

我还尝试把 export 放到 command 部分:

[program:sidekiq]
user=web
directory=/var/www
command="export REDIS_URL=redis://$REDIS_PORT_6379_TCP_ADDR:6379/0; bundle exec sidekiq -c 50"
redirect_stderr=true
autorestart=true

结果:

$ supervisord -c /etc/supervisor/supervisord.conf -n
2014-06-16 03:35:00,170 WARN Included extra file "/etc/supervisor/conf.d/sidekiq.conf" during parsing
2014-06-16 03:35:00,193 INFO RPC interface 'supervisor' initialized
2014-06-16 03:35:00,194 INFO supervisord started with pid 346
2014-06-16 03:35:01,197 INFO spawnerr: can't find command 'export REDIS_URL=redis://$REDIS_PORT_6379_TCP_ADDR:6379/0; bundle exec sidekiq -c 50'

又一次:

[program:sidekiq]
user=web
directory=/var/www
command="export REDIS_URL=redis://%(ENV_REDIS_PORT_6379_TCP_ADDR):6379/0; bundle exec sidekiq -c 50"
redirect_stderr=true
autorestart=true

结果:

$ supervisord -c /etc/supervisor/supervisord.conf -n                              
Error: Format string '"export REDIS_URL=redis://%(ENV_REDIS_PORT_6379_TCP_ADDR):6379/0; bundle exec sidekiq -c 50"' for 'command' is badly formatted
For help, use /usr/bin/supervisord -h

我到底哪里做错了?

编辑:

$supervisord --version
3.0b2

1 个回答

4

原来问题出在我对Python的字符串格式化语法不够熟悉。我需要在%()的后面加一个s,这样才能把格式类型设置为字符串。

最终的配置:

[program:sidekiq]
user=web
directory=/var/www
environment=REDIS_URL=redis://%(ENV_REDIS_PORT_6379_TCP_ADDR)s:6379/0
command=bundle exec sidekiq -c 50
redirect_stderr=true
autorestart=true

撰写回答