22 ms·
Don’t use environment variables for configuration
- danmur 6y agoMeh. Most configuration libraries I've used make all of these issues into non-issues. It's very useful to be able to set configuration with environment variables, even if you're loading from a file.
- Areading314 6y agoIf not env var then what is a good alternative? Config files could be considered "mutable global state". I have no issue with env vars for read only configuration. Programs that set env vars... thats where it gets very ugly.
- rurban 6y agoBut I keep putting more and more env vars into my programs. Enough command line switches already, but for debugging I always fall back to undocumented getenv's, rather than adding and removing silly -Dhexmasks.
- aarbor989 6y agoMaybe I live under a rock, but I feel like command line utilities taking environment variable arguments just isn’t that common of a practice? The only examples I can think of are when an argument is more of a “global variable” that many different commands may find useful such as JAVA_HOME, GITHUB_TOKEN, etc. For web applications and docker containers, environment variables fit easily into the deployment process and for all intents and purposes, are pretty much static.
- coldtea 6y ago>Maybe I live under a rock, but I feel like command line utilities taking environment variable arguments just isn’t that common of a practice? Nope, it's quite common. Many standard UNIX cli utilities take some environment variables (including things like LOCALE). Also common in scripts, setting up programming languages paths, etc. It's also not a bad practice, contrary to what the author says.
- mfontani 6y agoExamples I've used in the past few days, from memory - along the lines of: LC_ALL=C foo PAGER=cat man ls TZ=UTC date
- aarbor989 6y agoThese are good examples but I think these fit under my “global argument” umbrella. Imagine if every Linux command had a different argument name for the pager?
- saurik 6y agoLS_COLORS and GREP_COLORS are weirdly-specific... but arguably aren't!
- rubatuga 6y agoDamn, this guy has never worked a production environment before.
- q3k 6y agoI have, and I think he's right. I don't think picking apart the (assumed) experience of the author in this way is conducive to a high quality discussion.
- erulabs 6y agoI disagree with this post so strongly - having spent most of my career installing, configuring, and managing other people’s software. > The answer is that you, the end user, can not now. Every program is free to do its own thing and most do. If you have ever spent ages wondering why the exact same commands work when run from one terminal but not the other, this is probably why. If the same program is behaving differently between two systems - it can -only- be the environment that’s different. > Instead of coming up with a syntax that is as good as possible for the given problem, instead the goal is to produce syntax that is easy to use Oh to be a developer. The “best possible syntax” is a universe of possibilities - environment variables are, thankfully, limited to strings. If all programs had to be configured with a Turing complete config language - that would just be a programming language! Limitations can set you free. Sorry for the harsh tone. Please, and I believe I speak for most sysadmins, please continue to use environment variables.
- edem 6y agoI came here for this comment. I'm a developer and I have been using env vars for quite some time after I got burned numerous times by other options. I just can't see why I would use anything else.
- magicalhippo 6y agoI have no skin in this game, so to speak, so just curios. What kind of ways did you get burned by other things than env vars in a way in which env vars would not?
- edem 6y agoMostly configuration stored in the database (who configures the database) or 3rd party configuration services without an SLA and config files that are either present or not. Env vars are really simple since they are completely decoupled from the app and you can have default values for all of them. You just need a single class that loads all config on startup and you can go from there (or fail if you don't have the mandatory vars).
- tedk-42 6y agoAuthor doesn't know about https://12factor.net https://12factor.net and as another commenter mentioned, probably hasn't deployed something to a 'production' environment (or rather, doesn't know about separation of such environments in the first place).
- mrkeen 6y agoI don't know about https://12factor.net https://12factor.net either. But I was assigned a task last year to remove configuration from environment variables (for security reasons). I deployed my work to 'production'.
- kelnos 6y agoWell, sure, you shouldn't be putting secrets or other sensitive data in environment variables. But garden-variety configuration is fine to put in env vars. Seems like whoever assigned you this task didn't really know what they were doing.
- b0afc375b5 6y agoOops, I've been putting secrets in environment variables since I can remember. Your comment piqued my curiousity on why this is a bad idea. Found this: https://diogomonica.com/2017/03/27/why-you-shouldnt-use-env-variables-for-secret-data/ https://diogomonica.com/2017/03/27/why-you-shouldnt-use-env-... https://security.stackexchange.com/questions/197784/is-it-unsafe-to-use-environmental-variables-for-secret-data https://security.stackexchange.com/questions/197784/is-it-un...
- Cederfjard 6y agoWhat security concerns did that alleviate?
- mrkeen 6y agoAny third party code in our system can just read whatever's in the environment and POST it to some remote server.
- j1elo 6y agoI could agree with "don't only use environment variables for configuration", but at the same time, by all means do use environment variables to allow for easy overriding of configuration. I cannot but think of the large number of times that being able to quickly override some parameter with an env var has helped me achieve something which was not exactly intended by the original author. Also, env vars are the most common way to override configuration of software that has been dockerized (prepared to run in a Docker container). Plus, containers remember their initial environment, so there is no issue of running afterwards without the env var.
- RBerenguel 6y agoChanging a variable of an existing container without recreating or re-running the docker run command is tricky, though. With a configuration file mapped to an external folder it's "just" modifying the file and docker restart, with environment variables it's somewhat more convoluted. I don't think it is as clear-cut as the title suggest, each kind of configuration has its place.
- jpgvm 6y agoYou don't need to modify the Dockerfile to change environment variables at runtime. Also if you specifically want to modify a file and re-run the container look at --env-file arg to docker run.
- RBerenguel 6y agoThat's not what I'm saying, what you mention can be done indeed. What I say is that if you are in a machine with an already running docker container, one you don't have the corresponding `run` command of (i.e. you _can't docker run_ for whatever reason), changing the environment variables of that container is tricky.
- nickjj 6y agoYou could always run the `env` command inside of the container to get all of the set environment variables. Then you can define, reconstruct and run your container with whatever args you want. But yeah the env_file approach is the way to go here. I've been using Docker in production since 2015 and never ran into your use case. I always had an .env file ready to go that was loaded in with env_file and always had control over being able to run the container with whatever command I see fit. And in cases where I have no control over how things are run (like Heroku), environment variables still work because a ton of hosting platforms expect you to set and read them for various configuration. And you can also commit an example env file to git with no secrets so developers can `cp .env.example .env` to get going in 1 second. The environment variable pattern is incredibly standard in the world of web dev.
- alexaholic 6y agoThe article is not against env vars per se as the title suggests. Instead it makes a case against undocumented features and improper use of env vars. It also complains about env vars being plain strings but fails to recognize config files are just plain strings without the appropriate parser. What stops anyone from putting JSON arrays in env vars?
- axaxs 6y agoThis post seems to ramble without much substance. The best argument, perhaps only valid argument, is lack of an array type. Easy to work around. The rest seems misguided or ridiculous. >There is no way to know which one of these is the correct form What? Of course there is. The author is also calling it mutable global state, and seems to reference an application becoming confused when ENV isn't set. This reads to me, perhaps incorrectly, that the author doesn't understand that envvars aren't and don't behave like shared global variables. That is, changing one won't affect running applications.
- mrkeen 6y agoEasy fix (if it's the shared, mutable state which bugs you): * Create one class responsible for ingesting env vars at startup. * Call it from main, and abort early with nice messages if it fails to read something. * Now you have a nice (preferably immutable) class which guarantees the config is in a 'good state', and is self-documenting because it lists all the keys it uses to lookup env vars with.
- trey-jones 6y agoThis is more or less the way I handle configuration in most applications that I create. +1
- david422 6y agoAgreed - this solution works well, and works nicely with statically typed languages.
- zrail 6y agoThis is essentially what I do in Rails apps. The only reference to an env var is in an initializer that sets an option in the global rails config structure.
- FunnyLookinHat 6y agoIn node.js there are quite a few packages that do exactly this - it's a great pattern and forces you to define which env values you will rely on in one place, rather than dripping them all over your codebase.
- marcrosoft 6y agoThe mutable state can be helpful. It is sometimes helpful to be able to change an app’s config without having to restart it. Ingesting the envs on startup into a class removes this ability.
- throwaway10110 6y agothats quite an antipattern in production. Immutable config via a config class that can exit early (prefereably startup) if there is a misconfiguration
- maskaler 6y agoMoving from tokenising files to end vars was one of the best choices I ever made. Life is sooooo much easier using env vars
- jek0 6y agoAfter years of struggling with config file in heterogenous production environments, I'll argue the opposite: environment variables are the BEST option to manage your configuration.
- mcv 6y agoMixed feelings about this. I strongly agree with some, but also feel it's missing the point in a lot of places. Environment vars should of course not be used to configure specific programs. Having an environment variable to specify the args with which to call a program is needless complication. Just pass it as an argument. Use a configuration file to configure the program. Environment variables should (only) be used to describe the environment. That should primarily be variables that transcend individual programs. Things like proxy settings are perfect for environment variables. (Well, almost; see below.) Perhaps the location of the configuration file, if that can vary per system (which it probably should be able to; hard-coded locations can also be a problem). But even then, environment variables can fail. I noticed that some Azure/Kubernetes-related commands on my work Macbook need to run with the proxy on, and others with the proxy off, so I created aliases to enable/disable this environment variable, which completely defeats the purpose of the environment variable. Maybe I should be able to configure this proxy per application after all. Or at least configure whether to use or ignore the proxy settings. And then there are applications that ignore the proxy env var for whatever reason, and require me to configure it specifically for that one program, again defeating the purpose of environment variables (I think npm does this). But when we deploy our application to different environments, our deployment configuration does set specific env vars so the application knows how to behave in that environment. It's what environment variables are for. But they're not a great fit. For example, we're currently in the process of migrating from AWS to Azure, and some things need to be enabled or disabled there. So we set some environment variable to 'false', except that environment variables are always strings, and in javascript, 'false' evaluates to true. Json configuration might actually make more sense here. So I don't think we can or should do without environment variables, but I think I agree they're overused, and often used badly.
- ben0x539 6y agoYeah, we have a service that needs to use a proxy for most calls, but one component mustn't use the proxy, in a way that iirc is not properly captured by a `NO_PROXY` entry. Now the abstraction breaks down and the service has some ugly special-case code. :(
- rossmohax 6y agoI wish there was wider adoption of configuration services. Something like Enovy xDS protocol, but for general configurations. Puppet & Co did it to some extent, but for the whole server. On boot it asks centralized service for a configuration, providing just server identity and some basic attributes (datacenter, rack, stage) and receives full server configuration. Implementing this pattern for a service itself, would make it easier to configure swarms of services. I experimented with using Open Policy Agent, where it dispatches exact configuration based on client identity and quite liked the result. Only downside is that it requires polling.
- neolog 6y ago> An environment variable can only contain a single null-terminated stream of bytes. This is very limiting. The same is true of command-lines and files. Computers can only use bytes.
- prussian 6y agoA files' contents are not effectively smuggled just because halfway through a file a NUL is in it, unlike environment or arguments.
- deleted 6y ago[deleted]
- legulere 6y agoYou can have both: write your code in a way that you pass it’s configuration. This makes code more testable and reusable. Now in the outmost layer where you start your program you get the environmental variables and pass them.
- qgadrian 6y ago"This is the way we have always done it so it must be correct!" != "This is the way we have always done and it works perfect for everybody!" I want to use env vars because: * I want to reuse builds and my systems have different behavior on different environments. * I want to override the default config sometimes * I don't want to expose sensitive configurations, and yet have them explicitly configure in my project configuration The post it's very opinionated and lacking any valuable point IMO.
- dustinmoris 6y ago> Environment variables is exactly this: mutable global state. Envvars have some legitimate usages (such as enabling debug logging) but they should never, ever be used for configuring core functionality of programs Doesn’t matter where configuration lives, the name itself suggests that it is by definition global mutable state, I mean that’s the whole point of it. And it doesn’t matter if it’s used to configure core functionality (e.g feature toggles) or secondary functionality. The whole purpose is to do exactly that :)
- lmilcin 6y agoNever trust an advice expressed in an absolute.
- ben0x539 6y agoWell, infer that it's not absolute but rather ironically depends on the kind of environment you're developing software for. <:)
- lmilcin 6y agoWhat I mean is that when an advice is expressed in absolute it tends to be a radical view on the problem. Radicals tend to dismiss things that don't agree with their world view and I am always wary of this. And you should to. I don't mean radicals can't be right. What I mean is you should be cautious about it.
- Igelau 6y agoI feel like this is one of those riddles with two doors, two guards, one always tells the truth, the other always lies.
- madsbuch 6y agoIt indeed seems like there are a lot of fundamental misconceptions in this article: > For comparison using JSON configuration files this entire class os problems would not exist. This is the trade-of between structure and embedding. Writing '{"ARG": "-Dfoo=\"bar bar\" -Dbaz"}' would satisfy the authors need for JSON but not really do any difference. The initial example is also wrong. There certainly are example where one would use variables defined in out scope. f v = f' 0 where f' n = v n
- deleted 6y ago[deleted]
- nyanpasu64 6y agoIMO, the author is writing from the perspective of Meson, a command line build tool used by individuals that takes arguments and caches them in a per-project file, whereas most of the negative replies are commenting from the perspective of sysadmins deploying software into homogeneous servers or Docker containers. Would make be a better program if MAKEFLAGS was not an environment variable? (IDK.) Would Git be a better program if the project directory was passed as an argument rather than as inherited state (the cwd)? (IDK.) Would less or nano be a better program if file paths were passed in as environment variables rather than arguments? (no.)
- Aeolun 6y ago> a command line build tool used by individuals that takes arguments and caches them in a per-project file That is literally one of the worst ideas I’ve ever heard of. And I’ve heard many bad ideas recently.
- maccard 6y agoWhat's the alternative? That's how make, cmake, msbuild, ninja,docker, and basically every other build tool I'm aware of works
- haolez 6y agoMake doesn't work like that.
- orthecreedence 6y agoWait, make has a global state? I was under the impression most make targets are stored somewhere in the project itself (like a build/ directory). I think this is a fine approach, BTW. I think global state should be avoided unless necessary.
- haolez 6y agoMake does what you tell it to do. While some projects have the setup that you've described, many others do not. Make will only check the timestamps of the generated assets and decide to build (or not) based on that.
- phtevus 6y agoNo
- junon 6y agoOh this guy again. This guy created Meson and has a pattern of being 1) Quite toxic and 2) Entirely dogmatic when it comes to software design. He shows no interest in discussing design problems with Meson and asserts his viewpoints as truth and fact, resorting to snide comebacks instead of having thoughtful conversation. Doesn't surprise me he wrote an article like this. Completely misguided and isn't rooted in reality.
- hjek 6y agoOkay, so when you write that this blog author, who made a post arguing how environmental variables are global mutable state, is quite toxic and resorting to snide comebacks instead of having thoughtful conversation, then that is just you engaging in thoughtful conversation about the issue (which is envvars), and not you making a toxic ad-hominem attack at all, right?
- sdevonoes 6y agoIt surprises me that people put more attention to the author than to the content. I have no idea who the author is, but his post doesn't seem to me toxic at all nor dogmatic. On the other hand, your comment sounds a bit toxic, to be honest: "because the author is X it must be that all of his articles are X as well".
- zackkrida 6y agothere's an astonishingly silly GitHub issue thread linked in the comments of the post: https://github.com/ninja-build/ninja/issues/1482 https://github.com/ninja-build/ninja/issues/1482
- trey-jones 6y agoThis flies in the face of pretty much every opinion I've heard from experienced developers in the past 5 years. Once someone said, "You should be using ENV for configuration" I started doing it, and I found it to be a better solution than I previously had. I am also open to dedicated config files, whether they set ENV vars or not. I'm open to the idea that ENV is not the only way, and I certainly believe that there are situations where other solutions are warranted, but my opinion right now is that this is wrong, and I perceive this also to be the prevailing opinion in our industry.
- jillesvangurp 6y agoYes. If you package software up for deployment on some server (i.e. you use something like Docker), environment variables are the easiest/only configuration mechanism at your disposal. Packages that don't support this, need some workarounds (e.g. dockerize to template some config file using environment variables) to be packaged up; which is annoying and extra work. Decent server software comes prepackaged in docker form these days. Which means environment variables are the way you control those unless you want to force your users to create their own docker containers just so they can fiddle with config files, which is a bit user hostile. Dedicated configuration files only make sense if you assume a writable file system is there. Which is a broken assumption on many containerized environments. There is a lot of legacy software that works that way of course. Some software allows doing configuration via config files and then allows overriding keys in those files with some naming convention via environment variables. That's a good compromise since that allows you to package up sane defaults that you override as needed via the environment. It does not have to be an either or type thing. Another common pattern is to allow overriding configuration via commandline arguments, which you can then gather in an environment variable and inject via docker. I do this a lot with JVM based software where we have a lot of -D options to override specific configuration value defaults via docker. Less clean than just having dedicated environment variables in the docker file but it works.
- emodendroket 6y agoDocker certainly supports mounting a configuration file on the host system. Might be a little messier but it’s not impossible.
- erdos4d 6y agoThis is crap.
- sedeki 6y agoI hope I don't get downvoted, but I think the OP has a point. Command line arguments will do, and perhaps even be better. Why are there so many harsh comments about this post?
- mdpopescu 6y agoThere are a lot of use cases. For example, I have 17 applications running on a system that need a connection string. When I need to change that connection string, I can 1) change 17 config files; 2) change 17 shortcuts containing command-line arguments; 3) change one env variable.
- q3k 6y ago> I can 1) change 17 config files; 2) change 17 shortcuts containing command-line arguments; 3) change one env variable. This seems like forcing the application to take the burden of your configuration system having shortcomings (like not being able to freely convert from a single source of truth into multiple generated files/command lines/...).
- zabzonk 6y agoOr change ONE file that contains the connection string.
- snidane 6y agoEnv vars are a built-in for key-value command line args. Why introduce some custom convoluted way into your app for kv args instead of this standardised approach. I can understand why some heavily used cli app would support a custom parameter pattern, eg. for ergonomics, but for majority of apps running as deployed services and not cli apps invoked 100 times a day, I don't see a reason to not use env args. I can run the following and introduce exactly zero parsing boilerplate into my app or invoking scripts. port=12345 color=green ./myapp.py Also - some apps have to be configured from file, others on the command line. Which parameter parsing library even supports that? Env vars support this out of the box.
- 6y ago
- prussian 6y agoI've endlessly debated with myself about this and have come to the conclusion there isn't really a good solution and the best choice is probably put as much in an actual file as possible. environment is sort of leaky and non-obvious . at least with a file there is something that is written somewhere that can be inspected and passed as an argument or as an environment variable. The only real positive I see with environment is that children of the process group basically get it for free, but that can be a negative in it of itself as well. If I have to pick between environment and arguments as configuration, I'd probably prefer arguments since the application would have to explicitly iterate over all the arguments and handle them in some manner, like assign them to some structure or global internal to the program.
- ben0x539 6y agoOkay, so, I don't think the author cares about the situation where your entire system is, like, 1) set env var 2) launch long-running network service 3) never spawn another process inheriting the environment. That's the trivial, happy case. This post is probably more useful if you look at it from the perspective of a system invoking many different processes that come and go, somewhat recursively, likely integrating many independently-developed codebases. With non-trivial use of environment variables, you're just back to arguing about dynamically-scoped variables vs. lexically-scoped variables (comparing environment variables to lexically-scoped global variables seems besides the point). There are uses for dynamic scope and it keeps getting reinvented, but we know it comes with gotchas and typically prefer lexically-scoped variables. eg., environment variables are handy because you can pass them to your grandchildren without the direct children needing to know about them. Environment variables are hazardous because you can inadvertently pass environment variables to your children without knowing you inherited them from your parent. Environment variables can save you from having to teach your program to pass on the correct configuration. Environment variables can damn you when your children rely on them and hence omit facilities to propagate configuration in some nuanced manner. etc. I'm taken aback by the rancor in our comments. It shouldn't come as a surprise that people developing different kinds of software arrive at different best practices. I'm enjoying this kind of post much more when resolving the cognitive dissonance by trying to understand where the other side is coming from and how the experiences that shaped our respective aesthetic intuition differ.
- bayindirh 6y agoI have a pet peeve about this attitude. These methods are being used for decades and well understood with all their advantages and disadvantages. One day, someone comes and tells that it's bad and considered harmful, and happily tells the only right way to do it. A flame war ensues then. I'm all for moving things forward and evolution, but can't we take a milder stance and move forward in a more peaceful way? Attacking something so well established because of personal reasons feels so wrong from my PoV. That thing wouldn't be a de-facto standard if it was too bad, right? I think we shouldn't play with the foundation that much.
- q3k 6y ago> That thing wouldn't be a de-facto standard if it was too bad, right? I disagree. Very often, the 'easiest' option wins, not the one that necessarily is the 'best', especially in the long term. Environment variables for configurations are fast and easy, and work well on the happy path - but break down quite fast when dealing with more complex cases (eg. more complex types than strings). They have a treacherous way of seeming the simplest and most pragmatic solution at first, but becoming a an untyped, underdocumented hairball after some time in more complex software. Furthermore, as long as environments have existed in UNIX and UNIX-like derivatives, their usage to configure the bulk of the behaviour of most services/programs are relatively new. The more old-school the service you deploy somewhere, the more likely it has a file-driven config. Indeed, sometimes it seems like 90% of the Docker code out there is converting environment variables into configuration files.
- emodendroket 6y agoSure, but everyone understands that option and knows the pitfalls. This is kind of the core of the “worse is better” mindset, which somehow seems to have disappeared from the collective consciousness even though Unix is bigger than ever.
- bayindirh 6y ago> I disagree. Very often, the 'easiest' option wins, not the one that necessarily is the 'best', especially in the long term. Thank you for your disagreement and discussion, honestly. Actually, I think using environment variables are a burden. Needs more documentation, more explicit warnings, a lot of handling, etc. So, environment variables are not the easiest way out there. Especially when almost any programming language has nice config file libraries out of the box. Instead these variables are added as a convenience feature for some frequent scenarios where tool needs to adapt itself to the environment it needs to run in, just before starting or needs to be run repeatedly with small, transient changes to the config. > Furthermore, as long as environments have existed in UNIX and UNIX-like derivatives, their usage to configure the bulk of the behaviour of a service/program are relatively new. This is not what I see in my career. Bulk of the applications we installed and ran used some forms of environment variables for runtime configuration of the tool/application. The reason for that the variable had a great deal of effect in the behavior of the program (which was generally scientific) and making multiple runs without modifying a file very effective. You need these runs to conduct research BTW, and you're on a cluster and jobs run long and whatnot. TBH, most of these applications also had configuration files or "sensible defaults" and they either created their default files if there was none. And if there was a file, the environment variable was acting as an override. So I had experimental software, fixed most of the parameters in the file and tried some other things by overriding some parameter(s) with an environment variable. Nothing was abused or misused. > Indeed, sometimes it seems like 90% of the Docker code out there is converting environment variables into configuration files. I've never seen it TBH, and if that's not documented well, it would be a big bag of fun for the users of that code.
- yawboakye 6y agoRelatedly https://boakye.yiadom.org/bikeshed/env/ https://boakye.yiadom.org/bikeshed/env/ In short, I'm in full agreement with the author on not implicitly using magic variables/values in our programs. Environment variables are fine so long as they're not read from within the depths of a function.
- bayindirh 6y agoOpenMP[0] wants to have a chat with you about the usage of environment variables for runtime configuration of applications and dynamic adaptations of software to environment they run in. [0]: https://www.openmp.org/spec-html/5.0/openmpch6.html https://www.openmp.org/spec-html/5.0/openmpch6.html
- emodendroket 6y agoI think these disadvantages can be mitigated by putting the code that fetches environment variables close to the entry point and pushing the values down as arguments. I’d also say that a lot of these things are problems with configuration in general and one should seek to minimize unnecessary configuration to avoid a lot of the associated headaches.
- r3n 6y agoIs there any good guide on how to use environment variables as config properly, especially on managing and deploying them to servers ? I am having hard time figuring these out. So I rarely use environment variables.
- kmstout 6y agoI was taught many moons ago that configuration, like ogres and onions, is best considered in layers: 1. default values: What will most users in most places find most useful/least infuriating? 2. configuration files (system-wide, then user): What will most users on this system want most of the time? What will this particular user want most of the time? 3. environment variables: How should this session (i.e., a potentially large series of related executions) be tailored? 4. command line options: What is most useful for this particular run? I was also taught that: - figuring out how to go from an option to the name of a corresponding environment variable to a line in a config file should be both straightforward and well documented; and - sometimes you need a more complex configuration than is cleanly supportable through any other method than a file. In such a case, the location of that file can itself be passed through options and the environment.
- llimllib 6y ago(for default values, make sure you consider safety too! for example a debug option that might show PII is likely to be most useful to most people using the program, but shouldn't default to on because if it were on in prod the consequences would be serious)
- hardwaresofton 6y agoMy guess for this is that some people have not had the good fortune of seeing software that followed this pattern and how nice it is. I thought it was common knowlegse that if really wanted to do configuration right on a given project, you do all 4 (with some library support) and you write your code to gracefully handle the right piece of configuration from the appropriate "override level" (again usually with the support of a good library). See also: Domain Driven Design[0] which (if you ignore the consultant-fodder and jargon that comes with it) is probably one of the best written guides of how you should abstract systems, just like the gang of four book is a good introduction to structures in program/algorithm implementation you're likely to see in real life. [0]: https://en.wikipedia.org/wiki/Domain-driven_design https://en.wikipedia.org/wiki/Domain-driven_design
- ziml77 6y agoI like layered config as well. It really should be the default way of thinking about config. Our custom application framework handles that exact sort of layering and it's wonderful. I give it an annotated class representing the config that I need and it handles populating the fields from the config and generating the help message if something is missing.
- vcanales 6y agoThis is such a bad take that it feels like it being in the frontpage might even be dangerous.
- AzzieElbab 6y agosure env vars are overused. some values simply do not belong in the environment, for example - credentials. however, i havent seen a more convenient method of injecting configuration dynamically without some error prone file watching mechanics
- josephcsible 6y agoWhy don't credentials belong in the environment? They're definitely not visible to other users there, as opposed to on the command line where they definitely are, or in a file where they can be if you don't set the permissions correctly.
- AzzieElbab 6y agoBecause with credentials in environment we now have to distinguish between private and public environment vars so we don’t accidentally log something we should not or expose security sensitive info in another way
- MrWiffles 6y agoOr you could store your config as an environment variable in JSON, like Cloud Found does. I mean, JSON is really just one big string after all...
- celeritascelery 6y agoNow every program and script needs a full JSON parser and to all agree where this JSON is located in the system.
- throw14082020 6y agoThe author says: // to call it you'd do first_argument = 1; second_argument = 2; int three = add_numbers(); This is, I trust you all agree, terrible. This approach is plain wrong. I agree, but I don't think everyone agrees. Just have a look at the apple APIs, their configuration options are all objects you have spend time configuring, then pass as an argument. I don't know why everything with Apple development beats around the bush. It's almost too object oriented. To be clear, Apple is more like this: let argument = Argument() argument.first = 1 argument.second = 2 let addRequest = AddRequest() adder.add_numbers(with: arguments) let mathRequest = MathRequest() mathRequest.perform([addRequest]) if let results = addRequest.results { // Do something with your results. } And yes though, Apple development makes me feel smart when I solve something that should've been documented.
- Macha 6y agoI think you're objecting to different things than the author. The author is complaining that there's no link or information that first_argument or second_argument are used by add_numbers. In comparison, in the Apple API example you've given, addRequest is explicitly provided to perform. What you appear to be objecting to is setting up potentially complicated config objects to pass rather than passing simpler arguments.
- zajio1am 6y agoStrongly disagree. Environment variables are, IMHO, best tool for some simple configuration in unix. They match perfectly with behavior of the ecosystem and other tools in it (like unix shell). Yes, if your OS is some unversal JS machine, then JSON would be better, if it is Lisp machine, then you would use S-expressions, but on Unix machine, environment/args are way to go. There are two realistic alternatives - config files and arguments. They have each their own niche, where environment is somehwere between them. Arguments are better for one-shot setting, not for some setting used always. You can use 'alias' to define shortcuts that always add some argument, but that is definitely more cumbersome. Config files are good for always/default setting, but are too rigid. Changing config files is equivalent of changing global variable in code, it has system/user-wide effect. While i can just change environment in this one shell and it will affect just commands executed from that shell. Also, config files are much harded to be manipulated from scripts, and use different syntax for each tool. Perhaps the ideal tool would allow every option to be set/changed from config file, environment and argument.
- CGamesPlay 6y ago> Perhaps the ideal tool would allow every option to be set/changed from config file, environment and argument. This is exactly what the most widely used golang configuration library does: https://github.com/spf13/viper https://github.com/spf13/viper
- jayd16 6y agoIts also what most of the entrprisey frameworks do. Spring will do this and I'm pretty sure ASP.NET has some form of it.
- mixmastamyk 6y agoI made something similar for Python, with an animal theme too, ha: https://pypi.org/project/tconf/ https://pypi.org/project/tconf/
- yrro 6y agoWhy I don't like environment variables: 1. I worry about programs dumping all their environment variables to log files - credentials are now on disk, ingested into log storage... 2. Environment variables are inherited by child processes by default. This is undoubtable useful. But it can also cause problems. I wish the ghosts of unix past had forseen the need for a way to mark particular variables as, say, 'sensitive' and 'noexport', allowing them to opt out of the default behaviour. It would have been so say to say "variables starting with _ are not inherited and should be censored when output", but we're about 40 years too late for that to catch on...
- maynman 6y agoIf you're a heathen like me, you sometimes store JSON configuration in environment variables https://mitchum.blog/how-to-store-json-in-an-environment-variable/ https://mitchum.blog/how-to-store-json-in-an-environment-var...
- arethuza 6y agoStoring the name of an "environment" in an environment variable and then using that to pick the appropriate configuration file is what .Net Core does for web apps and that seems to work fairly well. Then, of course, you have the fun of Azure Application Configuration and KeyVaults - which are fine once set up and your app is happy with them.
- _greim_ 6y agoI don't mind environment variables for config, but it really bugs me when libraries read them. I'd much prefer to front-load them into my app's entrypoint where I can see and control them.
- vHMtsdf 6y agoI don't have a strong opinion on this, but a comment in the article lead me to this discussion, which is just wild: https://github.com/ninja-build/ninja/issues/1482 https://github.com/ninja-build/ninja/issues/1482 I get a sense that the maintainers hold a similar sentiment as the author of this piece, but it's never expressed, but the frustration feels real.
- henvic 6y agoGreat post! A few months ago I wrote this about my experience with this (mostly based on my experience writing Go): https://henvic.dev/posts/env/ https://henvic.dev/posts/env/ IMHO almost always (with exceptions) pointing to a secret/value in a file is better. For all other things, flags passed on arguments are better.
- StreamBright 6y agoI never understood why an environment variable makes sense. A type safe configuration in something like Dhall makes much more sense. For secrets environment variables also a terrible idea. An encrypted vault is much better.
- renewiltord 6y agoThis makes sense. You can use a config file and a cli param to point to which config file. However, env vars have worked very well for me and so there's this difference between theory and practice. I haven't found the reason but ultimately the model that the AWS CLI uses is very ergonomic (default config < env var < CLI pointer to specific config).
- xorcist 6y agoGood point, not the best arguments. But somebody needs to say this. Configuration in environment variables are suitable for short options for commands that needs to be inherited to sub-commands. Great for things like LESS and http_proxy. Suddenly people start shoving all kinds of configuration for a specific instance of a software in environment variables. Often with an argument about how otherwise it's not "twelve factor". That's not great. I mean, it's nice and all, but it's quite literally a blog post from a guy on the Internet, not an argument in itself. Arguments against putting all configuration for a software instance in environment variables is that it's not suitable for non-ASCII and multiline data for a multitude of practical reasons, the storage space is limited, the actual size will vary for operating systems and overflowing this will not be obvious, and the fact that child processes will inherit this data. If there are keys and other secrets involved, child processes will receive a copy of this. In comparison, storing configuration in a file will have a much more well defined format, it can be written and copied just like any other piece of data, and the standard tools will control access to it. Things like AppArmor can limit access further to the single process. Configuration files has been used forever for a reason, it's a reasonable default choice. Environment variables should be used where they are suitable, for interactive tools and for globally shared settings.
- miloignis 6y agoClearly we shouldn't use environment variables for everything - I agree with the do-it-in-layers comments of others - but I was compelled to point out he's got it exactly backwards. He suggests that environment variables are mutable global state, when they're not, then suggests actually mutable global configuration files. Surely in his scheme about adding numbers this is equivalent to setting the numbers to add in an entirely different source file! Environment variables, on the other hand, are more like lexical scoping - you can shadow them, spawn a new shell with copies of them, override them for a single invocation and then have them go back, etc.
- ajarmst 6y agoThis attitude is how we ended up with Active Directory. One assumes that the author doesn't spend much time in a command-line environment. The option to set defaults for one's normal working environment is obviously of value, and environment variables are hardly exclusive of configuration files (~/.bashrc, makefiles, ...). The theory that complex syntax and statelessness are inherently good and cost-free is naïve to the point of parody. The author is correct that "this is the way we have always done it" isn't a good argument in and of itself to persist in a practice. However, they might be rewarded by a few minutes pondering a related idea: "if generations of people---many quite capable of modifying the system to use something else---persist in using something, it's possible they have a reason for doing so other than a deficit in competence or imagination."
- kodah 6y agoOn the facade environment variables may seem like they're orthogonal to global variables but they're not. Environment variables are scoped to the current process. This could be your shell, but it could also be a web server. This doesn't make them leak proof, but unlike global variables, environment variables have a scope. Environment variables are also used more widely as an API. Many CLIs have a command that when self-executed can act as a persistence layer in your shell. This functionality would be impossible without environment variables. You mentioned the other motherload, which is that environment variables are quite often, again, used to communicate in Makefiles. You can see the natural scoping if you start to kick off an ad-hoc shell process inside a Make target.
- gnulinux 6y agoI don't get this. From the same perspective you can argue global variables have scope too since they are "scoped to the current process". It's not like other processes can access your global variable, that's a very low bar for a scope.
- TrueDuality 6y agoThe difference here is that a running shell (including the shell environments that services run with in) are an abstraction layer about managing processes. Within that abstraction layer, each process can have its own unique environment variables that they can change and manipulate independently. That makes them not global. Within a process the top level abstraction is the process itself, and anything underneath (class, method, function) will be impacted if another sub-abstraction makes a change to a global variable.
- RocketSyntax 6y agoappdirs
- barbazoo 6y ago> For comparison using JSON configuration files this entire class os problems would not exist. Every application would read the data in the same way The issue they mentioned earlier remains, as it's not specific to env vars. What if you don't supply a config file? > The environment is now different. What should the program do? Use the old configuration that had the env var set or the new one where it is not set? Error out? Try to silently merge the different options into one? Something else? I'm really not a big fan of using env vars for configuration but there are cases where it's a good choice, for example running docker compose and passing a .env file that becomes the configuration for the container. I agree that it's not a very good way to configure an application in a "shared" environment. For instance, I'm not a fan of curl reading my HTTPS_PROXY env var and implicitly using that value. That should be controlled exclusively by a cli switch imho.
- xaduha 6y agoKeep it in one place and have an easy way to disable setting configuration through ENV variables altogether. Don't let it get out of hand by sprinkling it everywhere, that's all.
- tantalor 6y agoSomebody never heard of CGI?
- kevinmgranger 6y ago> For example suppose you run a command line program that has some sort of a persistent state. `$ SOME_ENVVAR=... some_command <args>` > Then some time after that you run it again: `$ some_command <args>` This is absolutely no different from the following: > For example suppose you run a command line program that has some sort of a persistent state. `$ some_command --some-arg=value <args>` > Then some time after that you run it again: `$ some_command <args>`
- goatcode 6y agoInteresting: I went into reading this thinking in the context of programs. However, reading the replies here has made me realize it wasn't constrained to just that. For programs, there are better alternatives, especially if you're using a deployment pipeline that has things like key-value stores. In general, environment variables are great, especially for things that have access, practically, to not much else, like shells.
- phtrivier 6y agoIf you don't mind, I'll keep doing the relatively sane thing: using env variable at the startup of my applications (and, as much as possible, never anywhere else), among other configuration sources (like text files), to create a struct / object / dict / whatever that represents the configuration, and that the rest of my code uses. If you see someone using `os.env["xxx"]` as an escape hatch for a mutable global variable, then, yes, it's probably not a good idea. But it's not configuration anymore, it's runtime state. (Although I suppose no one is going to hit HN front page by writing an article titled "Don't use global mutable state", except to make game programmers giggle ?)
- marcosdumay 6y ago> Environment variables is exactly this: mutable global state. Wait, a large point of configuration is exactly that they are read-only.
- peterthehacker 6y agoPydantic has a nice way to parse/validate a collection of environment variables into native python types using type hints [0]. It solves for some of the pain points the author mentioned in a clean way. [0] https://pydantic-docs.helpmanual.io/usage/settings/ https://pydantic-docs.helpmanual.io/usage/settings/
- peterthehacker 6y agoint first_argument; int second_argument; void add_numbers(void) { return first_argument + second_argument; } // to call it you'd do first_argument = 1; second_argument = 2; int three = add_numbers(); > This is, I trust you all agree, terrible. This isn’t really a case against environment variables per say but against global config variables generally. Whether it comes from the environment or a config file that state will be global. So the example of adding globally defined integers is obviously silly, but if you change those variables to a username and password strings then change the function to db_connect it makes sense.
- Blikkentrekker 6y agoNo, they aren't mutable global state, they are paramatrers which is something many languages support: the key difference by design is that their configuration only lasts for the dynamic extent of the call. An environment variable is not mutable global state, for if a process change one, then that change is inherited by it's children, but not by it's parent or siblings, and the change effectively stops existing once the process ends. — that's a very important design change that removes all of the problem with mutable global state. In that sense, they are more like thread local variables that are inherited by child threads. A configuration file is much more akin to global mutable state of a system.
- amelius 6y agoAnother nice one is chdir() and how it behaves between threads.
- icedchai 6y agoWhen you realize threading was added on late in the game with Unix, this is hardly surprising. Unix is process oriented.
- exabrial 6y agoThat's literally what they're for. Take for instance: DATABASE_URL is a fail-safe method of configuring. When you install the app in dev, the app can _only_ point to the dev database. If the variable is absent, the application fails to start. If the prod URL is accidentally put in the the dev environment, firewall rules would prevent the prod connection. Configuration is _best_ put into the environment, not the application itself.
- josephcsible 6y ago"Environment variables is exactly this: mutable global state." No it isn't. Every time you start a process, it gets a set of environment variables of its own, which won't be changed by any further changes in the parent process. This is the opposite of how global variables work and is exactly how function arguments work. The rest of the article isn't very good either. The examples of running a program with two different states and of trying to do nested escaping would both apply to any means of passing configuration. I also find it hilarious that the author suggests using JSON configuration files instead, which actually have many of the problems that this article falsely claims that environment variables have.
- codemac 6y ago> which won't be changed by any further changes in the parent process. You can attach to a process and call setenv in gdb, so there is a loophole somewhere. I'm not encouraging this, just pointing out that having a nice binary which reads config, cli, and environment once is still required. Regardless of how you pass that information into your binary.
- klyrs 6y agoThe old guru I learned Linux from always said: "The bugs I've spent the longest time tracing down have always been caused by environment variables. It was only when I started checking them first, rather than last, that I felt competent as a sysadmin." Truth is, you aren't going to get rid of them unless you make an operating system that doesn't have them (and good luck porting anything useful to it). This is poor advice, because it amounts to FUD -- those problems won't go away, but in telling people to avoid environment variables will quash their curiosity about them. This teaches people to only look to the environment last.
- nikisweeting 6y agoThe title should be "don't sprinkle environment variable reads all over your codebase", not "don't use environment variables". The problems proposed are easily fixed by: 1. read all your env vars at startup in a single function, then pass them down from there 2. don't invent your own serialization format, just use json or csv, both work fine in env vars. or use the env var to reference a file path that contains more complex values. As a devops engineer / sysadmin for going on 10 years now, I pretty strongly disagree with this article. Environment variables are so much better than the alternative. In the past, programs frequently invented their own configuration loading systems, but over the last few years containerization has strongly nudged most programs towards accepting env vars. The result has been a better, more consistent, and less surprising config experience for everyone, even non-container users.
- Communitivity 6y agoI've always used a mix of environment variables and a set of config files for my apps. Often the vars determine which config files are loaded, which mode the app operates in (expert,normal,beginner), and debug level. I never put security information in the env variables. I also always treat vars as unvalidated user input (i.e., apply sanitization and validation).
- oxplot 6y agoI've recently started developing unix tools with config passed entirely as arguments with a special argument called `--args-file` which takes a file or stdin and reads one arg per line. This is of course nothing new, but such a powerful pattern: - It lets you run things without the need for a config file (when testing/running interactively) - but on the other hand, you can still define arguments saved in a file for more permanent setups. - `--help` ends up providing all the doc needed to configure the tool. - It's less magical than env vars and doesn't leak into subprocesses by mistake. One pragmatic step further is to expand env vars using the shell `${VAR}` syntax for slightly more flexibility.
- hnarn 6y agoI don't understand how a blog post like this can garner, at time of writing, a hundred upvotes. Normally these types of strong statements "Don't do X/Don't use Y" are attention seeking titles with inversely proportional interestingness of its content. That's the first red flag. The second red flag is that the article is not proof-read: from just the first few minutes of skimming, I found two errors that make the text jarring to read (Persistance->Persistence & [you] can not now -> [you] can not know). Thirdly, the entire central point makes no sense. The author presents this argument to illustrate why environment variables are confusing: > The environment is now different. What should the program do? Use the old configuration that had the env var set or the new one where it is not set? Error out? Try to silently merge the different options into one? Something else? The answer is obvious to anyone that knows what environment variables are and how they work: if the variable is set, it should use it, and if it's not, it shouldn't. The author goes on (again, spelling error) to state that: > For comparison using JSON configuration files this entire class os (sic) problems would not exist. What is the practical difference between using a JSON formatted text file containing settings, and a text file containing environment variables and their definitions? For the situation we're discussing here, the answer is frustratingly simple: there is none. This post is a waste of time.
- athenot 6y agoYes. At the same time, the post missed an appropriate case for avoiding environment variables: when you want dynamic configuration for your services, where configuration values can be changed at runtime without requiring a full redeploy of all the instances. Of course, that brings its own set of complexity which should be carefully weighed against requirements. Environment variables are still one of the simplest—and yes, most deterministic ways—to alter behavior of a program.
- Out_of_Characte 6y agoSuch a shame, Enviroment variables are indeed difficult to work with sometimes, who sets them? in which file? Who can/will override them? typo's are also not being caught because editors dont have lists of possible variable and/or what value they are allowed to contain. you might also lose them on different containers. Enviroment variables should be part of cgroups in some way. I dont like that any program can modify the PATH variable as example. seems like a recipe for disaster in privilege escalation.
- motoboi 6y agoI think you're trying to say: don't use environment variables as a database.
- chriswarbo 6y agoCalling env vars 'global mutable variables' is pretty misleading. The example C code is a terrible strawman, and makes it appear that the author is simply unaware of some core compsci/programming concepts. Environment variables behave much more like dynamic variables (AKA dynamically scoped/bound variables), rather than global variables https://en.wikipedia.org/wiki/Scope_(computer_science)#Dynamic_scope https://en.wikipedia.org/wiki/Scope_(computer_science)#Dynam... In particular, we can override env vars for a particular call, without affecting anything else. For example, consider the following script: echo "BEFORE $FOO" FOO=bar printFoo printFoo echo "AFTER $FOO" If we run this script with 'FOO=foo', and assuming that the program 'printFoo' simply prints the 'FOO' env var, we will get: BEFORE foo bar foo AFTER foo The variable 'FOO' wasn't mutated (since the value remains the same across lines 0, 2 and 3); it's also not globally scoped (since line 1 saw a different value). Rather, each process is run with its own environment, whose initial contents is inherited from the scope that invokes the process; plus extras/overrides, like 'FOO=bar' above. Env vars are mutable, and mutating an env var acts differently to mutating a dynamic variable: dynamic scope looks up variables on the call stack, so mutations high up the stack will be visible after returning. Instead, env vars are copied from parent to child at each new scope (process), so mutations are only visible to that process and any subsequent subprocesses. In fact, that makes env vars even less 'globalish' and 'mutableish' than ordinary dynamic variables! For example: if 'printFoo' finished by mutating 'FOO' to equal 'baz', it wouldn't affect the above script at all. Even line 2, which "inherits" the script's FOO, would only be mutating its own copy of 'FOO', which doesn't affect the script's variable. In any case I highly recommend to avoid mutating env vars, for the same reason I avoid mutating any variables, regardless of language; unless there's a specific reason to. If we treat env vars in an immutable way, then they act exactly like dynamic variables. As an example of dynamic variables, consider the following Lisp code: (write-line (concatenate "BEFORE " FOO)) (let ((FOO "bar")) (printFoo)) (printFoo) (write-line (concatenate "AFTER " FOO) The '(let ((FOO "bar")) ...)' construct acts like the 'FOO=bar ...' of the script. Not only do I find env vars very useful for config, I also find dynamic scope is very under-utilised in "proper" (non-shell) languages. For example, dynamic scope is a great way to do dependency injection: rather than passing around extra arguments, or adding a bunch of private fields to objects, etc. we can just reference the dependency with a dynamic variable, and open a new scope whenever we want to set its value (at an application's entry point, or in a test, etc.)
- deleted 6y ago[deleted]
- telaelit 6y agoI think there are some valid arguments to be made against the use of envvars for configuration, but none of them were in this article.
- nickthemagicman 6y agoI think if machines are treated like single purpose cattle then environmental variables are fine. But for a single system with lots of different applications and functionality going on, you kind of run into the same problem as you have with mutable global variables.
- cmckn 6y agoIf my program needs more than a couple arguments, I prefer a YAML configuration file. I usually try to enable environment variable substitution in that file. This makes configuration more natural when/if the program is run in a container (you don't need to volume-mount a file); and it gives the user flexibility in how they configure the program. To each their own, I suppose.
- kristjansson 6y agoOne perspective from this thread: environment variables end up denoting different levels of persistence in interactive, server, and containerized applications. For interactive apps, environment variable configs tend to sprout up for _persistent_ configurations e.g. HOMEBREW_NO_AUTO_UPDATE - we want the behavior to change, but we don't want to pass a flag to make that change every time. For server-like applications, env vars denote a _transient_ change in behavior e.g. FLASK_DEBUG=1 python -m flask ... to turn on different behavior in that instance of the application. Persistent configuration changes go to a config file or similar. For containerized applications, env vars are back to denoting _persistent_ changes in configuration since we bake the values in to deployed containers via whatever orchestrator. TFA seems to be assailing the first perspective, which is actually reasonable. Sticking secrets and configuration into the shell environment for each tool is not great. Transient config via args and persistent config via files makes lots of sense. Even in that setting though, there is probably a role for environment variables when spooky-action-at-a-distance changes are required in sub (sub- (sub- ...)) processes / libraries where passing configuration through each caller would be a pain.
- elihu 6y ago> Environment variables is exactly this: mutable global state. Not really; environment variables can't be externally changed once they're passed in. If it were true mutable global state, some external process could change their value while a program is running. Or the program could change the value of the environment variable in the shell that launched it. Either of those would be horrifying. In other words, environment variables could be worse. They could also be better. My main objection to environment variables is that they're not a discoverable interface. Ideally, it should be possible to find out what environment variables a program accepts without running the program (or grepping the source code for "getenv"), and in most cases it should be possible to enumerate the valid values. Environment variables are just one of many things about they typical POSIX / ANSI C interface that have been around so long people don't even question it anymore.
- benlivengood 6y agoConfiguration should be parseable. Unix philosophy has been to use configuration files for anything much more complex than flags, which seems reasonable to me. Don't try to force structured configuration into an arrays of strings. Traditionally, I see flags as being very application-specific and environment variables being very generic. Environment variables control the behavior of shared libraries and the interaction with the operating system. That separation frees applications from worrying about name collisions between application and library configuration. The tradeoff Unix made between unstructured configuration (e.g. main(void *arg)) and fully structured configuration was probably wise. Arrays of strings with quoting rules are pretty flexible and human readable. It doesn't gives the full flexibility of the extreme approaches but has aged well. For example, anyone who is annoyed by environment variables is free to wrap every program they care about in a shell script that sets the environment from the flags they want. Anyone who hates flags can pass environment variables to their version of the script with a bunch of --flag=${MY_PRECIOUS} inside.
- tomphoolery 6y agoEnvironment variables, when used correctly, tend to work just about everywhere. That's why they're in use. It's the same reason why programs still install to `/usr/bin`, even though we're all very much aware that `/usr` is not "user direectories" and the whole idea of "userspace" vs "kernel space" is irrelevant in 99% of *nix installs these days (including containers).
- fatbird 6y agoHis example: $ SOME_ENVVAR=... some_command <args> Is wrong. SOME_ENVVAR is set only for the invocation some_command; at the next prompt, the value of SOME_ENVVAR is what it was before the invocation. To persist the setting of the value you need to export it: $ export SOME_ENVVAR=... some_command <args>
- rualca 6y agoThis blog post is so wrong and out-of-touch that it boggles the mind how it popped up in HN. The blogger's strawman to criticize the use of env variables is so mindless and outlandish that casts some doubt regarding the author's experience and know-how. Meanwhile I'll just say the following: * Any config input, whether passed through env variables or config files or command line arguments or external services or telepathy, is handled by clients. Sure, anyone is free to directly call getenv() from whatever corner of the project, but to handle any input properly you need to use dedicated clients to handle common usecases such as input validation, logging, provide sane defaults, and layer config settings.
- 1_player 6y ago> environment variables are mutable global state, therefore bad Wrong. They are immutable global state. There is no way of updating a process environment set after it's started. Apart from corner cases (execve), env vars are immutable, therefore act like constants. And constants aren't bad, are they?
- victorNicollet 6y agoI have only very rarely used environment variables in my own software over the last 20 years. The argument for their use that I have heard the most frequently has been "you would have to be an idiot to not use them" which has thus far failed to convince me. That, and its little brother "you must never have pushed anything to production" seem to find some echo in this thread. From what I could gather, the actual reasons that Other People use environment variables seem to be: - Other People use some tool for a reason unrelated to environment variables, and that tool happens to make environment variables extremely easy or convenient. A more pessimistic alternative: that tool makes everything inconvenient except for environment variables. Whatever that tool may be, I suspect that I am not using it. - Other People write programs that are invoked (I write programs that run continuously), and environment variables improve the ease with which programs can be invoked, which is a concept I never have to deal with. My programs load their configuration from files at startup ; configuration files are committed to git and included in the build ; secrets live in a remote key vault, with a local cache in case of unavailability. Maybe in the future, I will discover something that environment variables greatly improve about this. I don't know.
- mk81 6y agoI lol-ed.
- BerislavLopac 6y agoThe most common problem that I've encountered with using environment variables for configuration is that developers often add them ad-hoc, in the module where the configuration is needed, making it impossible to have a clear idea of all the configurable options in a program. The solution is not to get rid of env vars, but to have a mechanism that centralises the confirguration in one place; this way all the options are easy to locate, and they can be defined in multiple ways. Shameless plug, FWIW: figga is my humble contribution to this area for Python: https://github.com/berislavlopac/figga https://github.com/berislavlopac/figga