Skip to content

Environment variable for Broker URL is prioritized over app settings #4284

Open

Description

@Checkroth

Checklist

  • I have included the output of celery -A proj report in the issue.
    (if you are not able to do this, then at least specify the Celery
    version affected).
  • I have verified that the issue exists against the master branch of Celery.

Steps to reproduce

Celery version: 4.0.2 (latentcall)
Issue is about the celery python app, which we are currently using with django (not django-celery).
Issue can be seen here: https://github.com/celery/celery/blob/master/celery/app/utils.py#L85-L106

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.

Activity

  1. Checkroth commented on Sep 25, 2017

    @Checkroth
    Author

    I have added a test to demonstrate the issue:

    #4285

  2. added this to the v4.2 milestone on Dec 19, 2017
  3. modified the milestones: v4.2, on Jan 13, 2018
  4. ant31 commented on Feb 15, 2018

    @ant31
    Contributor

    I don't see an issue here, many software prioritizes environment variable over conffile when both exist.

    Things to eventually improve:

    • document what's the precedence order
    • log from where the configuration is taken
  5. thomas-riccardi commented on Feb 15, 2018

    @thomas-riccardi
    Contributor

    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.

  6. Checkroth commented on Apr 24, 2018

    @Checkroth
    Author

    @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.

    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.

    @ant31 's improvements ( #4284 (comment) ) would also be much appreciated.

  7. auvipy commented on Apr 25, 2018

    @auvipy
    Member

    may be doc changes worth mention it?

  8. modified the milestones: , v4.2 on Apr 25, 2018
  9. modified the milestones: v4.2, v4.3 on May 25, 2018
  10. added
    Sprint Candidate
    on Oct 11, 2018
  11. removed this from the v4.3 milestone on Nov 17, 2018
  12. 15 remaining items

  13. tomwojcik commented on Mar 14, 2022

    @tomwojcik
    Contributor

    Thank you @illagrenan for this example. My current worker file looks like that

    import os
    from celery import Celery
    from django.conf import settings
    
    
    if not settings.configured:
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")  # pragma: no cover
    
    # https://github.com/celery/celery/issues/4284#issuecomment-1067196398
    os.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.

  14. larrybotha commented on Jun 22, 2022

    @larrybotha

    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:

    1. create a secret with Docker
      • secrets are then exposed via /run/secrets/[secret_name] files inside containers
    2. environment variables are assigned the path to the secret, e.g. CELERY_BROKER_URL=/run/secrets/celery_broker_url
    3. 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):

    1. user-defined configs
    2. command line values
    3. environment variables
    4. 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:

  15. modified the milestones: 5.2.x, 5.3.x on Jun 29, 2022
  16. lafrech commented on Aug 30, 2022

    @lafrech
    Contributor

    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).

  17. auvipy commented on Dec 8, 2022

    @auvipy
    Member

    I would be happy to review any contributions in this area.

  18. modified the milestones: 5.3.x, 5.5 on Jun 25, 2024
  19. stevelacey commented on Sep 27, 2024

    @stevelacey

    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.

  20. ryanhiebert commented on Dec 21, 2024

    @ryanhiebert
    Contributor

    Differently from @larrybotha, I think that the right precedence ordering is

    1. Command line options (--celery-broker)
    2. User-defined configuration (celeryconfig.py)
    3. Environment variables (CELERY_BROKER)
    4. Library-defined static configuration file (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.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.

  21. NathanAP commented on Jan 17, 2025

    @NathanAP

    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.

    from celery import Celery
    
    celery = Celery("tasks", broker=os.getenv("CELERY_BROKER"), backend=os.getenv("CELERY_RESULT"))
    
    celery.AsyncResult(id=my_task_id)
  22. modified the milestones: 5.5.0, 5.7.0 on May 14, 2025
  23. modified the milestones: 5.7.0, 5.8.0 on Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions