You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Environment variable for Broker URL is prioritized over app settings #4284
My team had a misunderstanding about Celery settings and environment variables (we thought the celery app would set the config from environment variables automatically using config_from_object). We had CELERY_RESULT_BACKEND and CELERY_BROKER_URL set in our environment variables. This worked perfectly for a while, until we started doing operations that relied on the result backend.
It took a while to figure out why the broker url was working fine but the backend was not. After some investigation, I realized that the broker url wasn't set at all, and that the call to broker_url was actually using the environment variable we had set instead of the app settings.
Expected behavior
Celery broker settings should take priority. Currently, even if we had properly configured celery, a stray environment variable could break our application.
Ideally, the broker url would not be read from environment variables at all, at least not at the level in which it is currently read, as this only causes confusion. I am not familiar with why it is implemented this way, but it looks like it is probably a bit of legacy code.
Actual behavior
Celery broker url is read from environment variables before app settings.
Reacted by Max Smolens, Wayne Chang, Václav Dohnal, Kenneth Nwafor, Tomasz Wójcik, Leem0sh, Larry Botha, Bryan Weber, drift2galaxy, Larissa Leite and 8 more
This is not the current issue: there is no conffile involved in the scenario.
The issue is precedence of env vars over explicit configuration passed as Celery constructor or otherwise edited by explicit code (dev controlled), not a user controlled conf file vs env var.
Reacted by Ed R2, Omer Katz and Bruno Toshio Sugano
My main concern would be that it seems like your settings are being taken when you explicitly set them, but Celery is "magically" picking up environment variables that you might not even be aware that you have set.
The issue I'm raising is a personal issue I guess, where I feel that any explicit setting in your code should take priority over automatic settings (like those from environment variables). I have since realized that prioritizing Environment variables is by design so I have closed my pull request regarding the issue, however I have a few thoughts on mitigating confusion in the future:
On the PR adding tests demonstrating this issue ( #4285 ) @georgepsarakis brought up a point that would at least remove the confusion for anybody else in the future.
However your test seems to raise another question regarding the behavior of ConfigurationView and properties in sub-classes such as Settings.broker_url; an exception should have been raised when you try to set a value for broker_url and this does not happen. Perhaps AttributeDictMixin is responsible for this.
If your broker_url is set, and you make a manual change that wouldn't actually have any influence on your Celery configuration, Celery should tell you with an exception or a warning log or something instead of just silently eating the manual setting.
Reacted by Antoine Legrand, Ed R2, Ramil Aglyautdinov, Omer Katz, Tomasz Wójcik, Jonathan Meier, Bryan Weber, tyhayeswbs, SebastianDix, F. Torkashvand and 1 more
Thank you @illagrenan for this example. My current worker file looks like that
importosfromceleryimportCeleryfromdjango.confimportsettingsifnotsettings.configured:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") # pragma: no cover# https://github.com/celery/celery/issues/4284#issuecomment-1067196398os.environ["CELERY_BROKER_URL"] =os.environ["SOME_ENV_VAR"]
os.environ["CELERY_RESULT_BACKEND"] =os.environ["REDIS_URL"]
app=Celery(
"project_name",
# broker=settings.CELERY_BROKER_URL, # doesn't matter what you set here
)
app.config_from_object("django.conf:settings", namespace="CELERY")
I was so confused as to why it doesn't work as settings.CELERY_BROKER_URL is set correctly and I have no control over env variable name, but this simple "overwrite env var with another env var" when needed fixed this weird issue.
celery==5.2.1
django==4.0
I use django-health-check in my project and when I access the dashboard, it says that the results backend is not configured. Doing the same trick for result backend fixes this issue as well.
I'm experiencing the same precedence issues when using Docker secrets, .e.g deploying using docker stack deploy instead of docker compose up
With Docker secrets, values are obtained as follows:
create a secret with Docker
secrets are then exposed via /run/secrets/[secret_name] files inside containers
environment variables are assigned the path to the secret, e.g. CELERY_BROKER_URL=/run/secrets/celery_broker_url
the value of the secret is then read from the path assigned to the environment variable
With environment variables having higher precedence, Celery uses the following invalid broker URL: amqp://guest:**@%2Frun%2Fsecrets%2Fcelery_broker_url:5672//
As a workaround, I'm manually overriding the Celery env vars with the values read from the secrets, as suggested in #4284 (comment) and #4284 (comment)
This was surprising to me - I expected the priority to be something along the lines of (highest to lowest):
user-defined configs
command line values
environment variables
config file
As an aside, evaluating the environment variables of a running container shows that the updated values are not exposed.
EDIT: turns out that even official Docker images rewrite secrets to environment variables, and Kubernetes supports this out of the box:
I came here looking for the opposite: a way to configure Celery with env vars.
Setting an env var with an absolute path to a config file (#5303) would be fine.
Setting an env var per setting is fine, too.
I'd keep the behaviour and document it.
I don't buy the "celery picks stuff from random forgotten vars in my env" argument. When deploying, environments are supposed to be clean. And using env vars is a common way of overriding stuff.
Sure, logging where each value is picked up could be nice, to save people from the issues described in comments above (not knowing an env var is overriding an explicit value).
Reacted by Bjoern Stiel, Sean Xiang, Alejandro Giacometti, Guy Hoozdis, Alfonso Montero López, Jorrick Sleijster and Etienne Landuré
I switched an application to a different broker url prematurely as a result of this, I have this django setting: CELERY_BROKER_URL = env.str("CLOUDAMQP_URL", None), and intended to switch to using CELERY_BROKER_URL as the env var later, so naturally; set the env var ahead of shipping that change, and was surprised to see it take immediate effect.
Because user-defined configuration is able to implement 3 & 4, it makes sense that it takes priority over those, because it can customize their behavior. But celeryconfig.py shouldn't take priority over command line options because the settings file isn't able to customize command line option parsing. To override that, you'd need a different type of hook.
Reacted by Antoine Legrand, Jonas Dedden and Mykhailo Polishchuk
Reeeeeally important issue. Setting CELERY_BROKER_URL and CELERY_RESULT_URL to another value other than the default never made any difference for me, so its better to set another variable and use it.
Activity
Checkroth commentedon Sep 25, 2017
I have added a test to demonstrate the issue:
#4285
ant31 commentedon Feb 15, 2018
I don't see an issue here, many software prioritizes environment variable over conffile when both exist.
Things to eventually improve:
thomas-riccardi commentedon Feb 15, 2018
This is not the current issue: there is no
conffileinvolved in the scenario.The issue is precedence of env vars over explicit configuration passed as
Celeryconstructor or otherwise edited by explicit code (dev controlled), not a user controlled conf file vs env var.Checkroth commentedon Apr 24, 2018
@thomas-riccardi is correct.
My main concern would be that it seems like your settings are being taken when you explicitly set them, but Celery is "magically" picking up environment variables that you might not even be aware that you have set.
The issue I'm raising is a personal issue I guess, where I feel that any explicit setting in your code should take priority over automatic settings (like those from environment variables). I have since realized that prioritizing Environment variables is by design so I have closed my pull request regarding the issue, however I have a few thoughts on mitigating confusion in the future:
On the PR adding tests demonstrating this issue ( #4285 ) @georgepsarakis brought up a point that would at least remove the confusion for anybody else in the future.
If your
broker_urlis set, and you make a manual change that wouldn't actually have any influence on your Celery configuration, Celery should tell you with an exception or a warning log or something instead of just silently eating the manual setting.@ant31 's improvements ( #4284 (comment) ) would also be much appreciated.
auvipy commentedon Apr 25, 2018
may be doc changes worth mention it?
15 remaining items
tomwojcik commentedon Mar 14, 2022
Thank you @illagrenan for this example. My current worker file looks like that
I was so confused as to why it doesn't work as
settings.CELERY_BROKER_URLis set correctly and I have no control over env variable name, but this simple "overwrite env var with another env var" when needed fixed this weird issue.I use
django-health-checkin my project and when I access the dashboard, it says that the results backend is not configured. Doing the same trick for result backend fixes this issue as well.larrybotha commentedon Jun 22, 2022
I'm experiencing the same precedence issues when using Docker secrets, .e.g deploying using
docker stack deployinstead ofdocker compose upWith Docker secrets, values are obtained as follows:
/run/secrets/[secret_name]files inside containersCELERY_BROKER_URL=/run/secrets/celery_broker_urlWith environment variables having higher precedence, Celery uses the following invalid broker URL:
amqp://guest:**@%2Frun%2Fsecrets%2Fcelery_broker_url:5672//As a workaround, I'm manually overriding the Celery env vars with the values read from the secrets, as suggested in #4284 (comment) and #4284 (comment)
This was surprising to me - I expected the priority to be something along the lines of (highest to lowest):
As an aside, evaluating the environment variables of a running container shows that the updated values are not exposed.
EDIT: turns out that even official Docker images rewrite secrets to environment variables, and Kubernetes supports this out of the box:
lafrech commentedon Aug 30, 2022
I came here looking for the opposite: a way to configure Celery with env vars.
Setting an env var with an absolute path to a config file (#5303) would be fine.
Setting an env var per setting is fine, too.
I'd keep the behaviour and document it.
I don't buy the "celery picks stuff from random forgotten vars in my env" argument. When deploying, environments are supposed to be clean. And using env vars is a common way of overriding stuff.
Sure, logging where each value is picked up could be nice, to save people from the issues described in comments above (not knowing an env var is overriding an explicit value).
auvipy commentedon Dec 8, 2022
I would be happy to review any contributions in this area.
stevelacey commentedon Sep 27, 2024
I switched an application to a different broker url prematurely as a result of this, I have this django setting:
CELERY_BROKER_URL = env.str("CLOUDAMQP_URL", None), and intended to switch to usingCELERY_BROKER_URLas the env var later, so naturally; set the env var ahead of shipping that change, and was surprised to see it take immediate effect.ryanhiebert commentedon Dec 21, 2024
Differently from @larrybotha, I think that the right precedence ordering is
--celery-broker)celeryconfig.py)CELERY_BROKER)pyproject.toml)Because user-defined configuration is able to implement 3 & 4, it makes sense that it takes priority over those, because it can customize their behavior. But
celeryconfig.pyshouldn't take priority over command line options because the settings file isn't able to customize command line option parsing. To override that, you'd need a different type of hook.NathanAP commentedon Jan 17, 2025
Reeeeeally important issue. Setting
CELERY_BROKER_URLandCELERY_RESULT_URLto another value other than the default never made any difference for me, so its better to set another variable and use it.