DEV Community

Cover image for Stop Using .env Files Now!

Stop Using .env Files Now!

Gregory Gaines on September 19, 2022

Table Of Contents Hello Reader The problem with .env files Storing the .env file Updating a secret config Versioning ...

Displaying a subset of the total comments. Please sign in to view all comments on this post.

Collapse
 
ravavyr profile image
Ravavyr

I get it...you're like overly cautious.
After years and years of dealing with hundres of sites/apps/applications I can tell you one thing.

NO ONE gets hacked via their .env file. Ever.
First of all, it's really easy to lock it down so no one can access it except for the devs who need access. At some point there's at least one human being [preferably 2 in case one gets hit by a bus] who should know where and how to access and change all your passwords. Therefore having them in one place is just as safe as having them in 20 different places where you will absolutely 100% guaranteed forget some the next time you need to update things or something is on fire.

Overly cautious security leads to a mountain of steps to get to sensitive info that just hurts development and recovery times more than it helps to actually protect anything.

In other words...it's a pain in the buttocks. Don't do it.

Use .env files and learn the few steps it takes to protect them. There is NOTHING wrong with that.

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

Sounds like more work in my opinion. With a config server, there is no need to trust the "2 devs" since the server has permissions and access restrictions so only permitted devs can add secrets without viewing existing ones.

I don’t think it’s overly cautious, it’s being modern. There is no mountain of steps. Whitelist your application and use the config url like the examples in the article, easy and no pain in the buttocks.

Please re-read the article, I explained how easy recovery (roll backs) and development time is simplified using a config server. I COULD use a .env file and take steps to secure it, or I could live in 2022 and use a config server with permissions, auth, versioning, real-time updates, and an audit trail for extra security.

Personally I don’t want my secrets being stored in a glorified text file.

Thanks for the comment!

Collapse
 
trizz profile image
Tristan

Personally I don’t want my secrets being stored in a glorified text file.

So you store them at an external company? What if they are down, or have a data breach? (They are a bigger target than most of the websites). I'd like control over my secrets and not be dependent on third parties for such important stuff, and storing them in a .env is perfectly fine with the precautions and correct configuration mentioned by @ravavyr

Also, those services are not free. True, you can self-host HashiCorp Vault, but that costs also money.

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

True, nothing is full proof. But that's why we choose techniques or companies that gives us the best guarantees.

Also no matter how secure you keep that .env file, you are giving someone FULL view of all secrets whenever its updated.

The services I listed have free tiers. HashiCorp can be self hosted for free forever, Google Cloud has a free tier for 6 secrets, AWS has a generous free tier for storing configs in parameter store.

If you don't want to go with an external company and want full control over your secrets, thats fine. There are free, open-source, or self-hosted alternatives. There's Spring Cloud Config, Github Secrets (if you trust the company enough), or roll your own.

Thread Thread
 
teamradhq profile image
teamradhq

I think the point that @tristan is making rather well is that your recommendation is just increase the surface area of your vulnerable systems.

The mindset that doesn't even trust employees with private information would deem providing that information to a third party (especially a faceless tech company) to be less secure than, keeping it contained within a closed system that is completely under their control.

The arguments you're offering for using a third party to host private information are actually the arguments against using such services. They are the weak points: If a system is compromised, it's almost certainly due to leaky abstractions like this...

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

It's an increase in surface area, but with the benefits I listed above.

Its not distrusting employees, it's being safe and following a secure practice. I don't know about faceless companies, I mentioned Google, AWS (which is the leading in the market for cloud) and other credible companies which provide a config service. I may be a little bias since I am a Google employee.

And if thats the case, why trust anything? Why host private code on Github or deploy on Digital Ocean? Its for the ease and guarantee.

I also mentioned open source config servers that you can host or deploy yourself.

If a system is compromised, most likely its from using bad practices...

Collapse
 
dbroadhurst profile image
David Broadhurst

.env files should only be used locally in a dev environment. Not sure using them in production is a thing anyone does?
Using something like KeyVault for production makes sense but I prefer to use CI/CD secret services that github / gitlab provide. Makes sense to me that secrets belong to the build / deploy process.

Collapse
 
fourixai profile image
Tim Gaul

A word of caution with this approach - make 100% sure you're not exposing your secrets in your artifacts!

Collapse
 
teamradhq profile image
teamradhq

Can you explain why? If you're configuring secrets in your environment at the build step, they would still be accessible in the deployed system, thus no less vulnerable than if they're in a .env file aren't they?

I mean, if I have enough privilege to access a private file on a server, then theoretically, I can inspect the server's environment anyway.

I just feel like I'm missing something here...

Collapse
 
dbroadhurst profile image
David Broadhurst

Using secrets in CI/CD adds an additional level of protection for secret values through additional access controls but it isn't the only security needed. Assume you have a public repo but want to keep the secrets safe from people who have access to the source code, or you are a company with contractors who need to access the source code but should not have access to secrets.

If someone is able to access the server then other security should be considered such as using a VPC for private API's. Security should have lots of layers, protecting secrets by moving them outside the source code is just one layer.

Collapse
 
xgenvn profile image
Brian Ng

I think this depends on what kind of secrets. CI/CD secret can be used for CI/CD, eg: secrets to access Docker, K8s cluster, artifact stores ... Application secrets are different layer, so we need extra tool to provide those. All artifacts should be stateless, loading application secrets is likely effect that happens on runtime instead build/deploy time.

Collapse
 
martinmuzatko profile image
Martin Muzatko

It is myth busting time.

1. .env files are unreliable

Having the environment settings come via network adds a whole lot of overhead.
A lot of bad things can happen.

  • The centralized server providing the env can go offline - making my app not able to start
  • The centralized server could update, and then rename an env, that my app isn't expecting - crashing my app on the next restart
  • The centralized server could have an expired certificate - which will deny me my apps required environment vars
  • My app could be hosted offline, e.g. industrial applications where I only sometimes want to connect to the internet, but not at the start of my app - making my app not able to start without an internet connection (unless I cache the env, which leads us back to having local .env files alltogether)

You can by all means make a web service reliable. But how is an external web service more reliable than a file I have access to locally?
Sure, you can write bad code that allows attackers toaccess arbitrary files. But you might as well leak your environment variables even when you would retrieve them through a central environment provider. Object property injection is a thing. Essentially allowing you to instruct your server to serialize and send you the env via any API.
There is absolutely nothing from preventing you to write bad code. No matter if env is directly injected to the app or read from an .env file.

2. .env files have no access management

You can. Both locally and remotely.
How do you run your apps? If I run my docker containers, I can have my compose file read from an .env file and provide that to the containers. The app doesn't even need to know an .env file exists. But the only user starting apps would have access to the .env file. You can control very well on any system who is going to be the guy that gets to run apps.
Secondly, you can also manage access who is allowed to read and write the .env file.

3. .env files have no versioning

Check your .env file into git - no, not the public project. Create a separate repository that you can make private and only give access to limited people.

4. .env files have no safe updates

There is a little bit of lack of tooling here maybe, but you can create a contract between your app and what environment it expects.
In TypeScript and NodeJS you can simply overwrite the nodejs process.env interface, providing a clean contract between your app and the environment vars it needs. It would be even better, if you could generate that from a .env file. Problem solved.
When I roll out a new container, I update both my repo containing the new .env file for compose + the app.

Summary

.env files are a battle-tested and widely adopted and supported feature. They make deployments predictable and secure. If you have trust issues, then you can sufficiently lock it down and only inject it via docker containers.
I absolutely don't see a need for involving yet another server.

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

I'm not sure you read the article completely.

  • Yea, nothing is full proof; anything can go down, doesn't mean its not a viable option. When config variables are updated, they keep the same entry point ex. config/DB_PASSWORD/v1. Only the value is changed, this is how an paper trail is kept.

  • When that .env is updated the updated has full access to all secrets, no matter how secure that file is nothing will change that. My point wasn't that the file couldn't be stored properly.

  • The creaters of dotenv tell you not to commit it in your repo. Look below, tons of comments say the sme thing.

Summary
Please re-read the article, your points are not aligning with what I was saying. Yea its widely adopted, but change takes time.

Collapse
 
wuya666 profile image
wuya666

From what I understand , he's more like talking about a file-based config management solution, with git-based version control, meaning a dedicated private git service to manage the config file versions not exposed to outside access, that is quite different from "commit it in your repo" which means more about committing it in your application code repo.

Also you can easily have a system that automatically merge multiple config files into one .env file, which should not be directly accessible to anyone, so people updating the individual config files won't have access to configs in other files.

Like I said, you can have a file-based solution that achieves more or less the same goals as a database-based solution, which may be easier or harder to implement depending on your specific situation and needs. After all, databases are file-based solutions themselves, they too store data in files (well, some store non-persistent data in memory, but you get the idea :P )

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

Sounds interesting but still opening one .env exposes all secrets in it. A config server mitigates that risk while giving feature like audit logs and automatic secret rotation.

You also get the benefit of a ui if you care about that.

Thread Thread
 
wuya666 profile image
wuya666

The point is in such a file-based config management solution no one should be able to directly open the .env file, it should be dynamically generated and managed by the system, more akin to a "flat database file" if you like to think that way. And features like audit logs and automatic secret rotation can be implemented with no more than a couple dozen lines of code, without the need of a config server. Like I said, the main point of your post is actually not about "config servers" (albeit you are advocating their usage), but rather about storing the config data in remote databases vs. local files/environments.

And the existence of a UI can be a pro or con in the case of config administration depending on specific needs. It's also quite trivial to setup a simple database admin UI if you decide to store config data in remote databases anyway.

Thread Thread
 
gregorygaines profile image
Gregory Gaines

Honestly at this point you are just implementing a config server yourself. Every feature I mention you are saying just write it. If that's what you want to do by all means. We can agree to meet in the middle at this point.

Collapse
 
brense profile image
Rense Bakker

Do use .env files to define environment variables in local dev (which is what it is for). Don't commit .env files to your repo. github.com/motdotla/dotenv#should-... .env was never ever meant to define environment variables in production/hosted environments, its for local env ONLY.

Collapse
 
wiseai profile image
Mahmoud Harmouch

I don't think there's any harm in storing secrets in a .env file, as long as the file is kept safe and secure. In fact, I believe it's a good practice to follow the Twelve-Factor App's recommendations.

In their chapter on Config, they state that config should be in environment variables. This is good advice to follow, as it can help keep your application secure.

Moreover, by taking the necessary precautions, the risks of storing secrets in a .env file can be minimized. For instance, be sure to keep your .env file in a secure location and make sure that only authorized personnel have access to it. Additionally, you should encrypt any sensitive data that you store in your .env file.

By following these guidelines, you can ensure that your secrets are safe and secure while still being able to take advantage of the benefits of using a .env file.

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

This doesn't solve that anyone who updates it will have access to all your secrets in plain text. No matter how secure the .env it doesn't change that.

Also, environment variables are global to that machine, if someone gains access then they can read out your variables. This was one of the main techniques when the Log4J was exploited.

Collapse
 
wiseai profile image
Mahmoud Harmouch

As I mentioned, it's essential to encrypt your secrets rather than storing them as plain text. This way, even if someone can read your env variables, they won't be able to use it because it is a useless scrambled string of characters. Additionally, you can set the file permissions so that only the owner can read it, further protecting your secrets. Take the following Unix command as an example:

chmod 400 .env
Enter fullscreen mode Exit fullscreen mode

This will ensure that only the file owner can read it and that no one else can access it. This is a great way to keep your sensitive information safe and secure and ensure that only those who need to see it can do so.

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

What about sharing a secret to other? With a config server it’s as simple as ‘corp.secrets.com/config/DB_PASS/v2’.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

In this case, you can create an Inbound firewall rule or add an entry in the ACL to allow only specific users to access this file.

Thread Thread
 
gregorygaines profile image
Gregory Gaines

Again giving full access to every secret in the file to that user.

Collapse
 
click2install profile image
click2install • Edited

Despite the grabby article headline that I usually avoid on principle. I vehemently agree that .env was and is a terrible idea from multiple viewpoints, including software delivery and security. The best solution though, is to use passwordless identities to establish trust then nobody, including developers, need to know any secrets and when they leave the organization their access leaves with them. PKI should be considered first, not last.

Collapse
 
anderspersson profile image
Anders Persson

Great article.
I worked at a company using docker, we build docker without any user inside, eg you could use the service it provids but it hade no user inside to access.
If we hade to fix any thing, just build a new one.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
jamesmortensen profile image
James

If you're an experienced security consultant working with other experienced security consultants, I'm confident no one will commit that file, but most developers who are not in the security field just don't think that far ahead.

In my experience, someone will eventually commit that file. It won't be you or me, but someone at some point will do it, and it also might not be discovered for months until someone like you or I does an audit and discovers it in the commit history.

With that said, people can still misuse the config servers and secret managers too. At the end of the day, the tools are only as good as the people using them.

Collapse
 
tillt profile image
Till

The author seamingly has no idea of git ignore/exclude (decades old), the concept of pipeline variables (which obviously can be files or generate files as well) and the multiple risks which come when you hand over your business secrets to third party companies or tools (regarding technical security as well as business stability).

So I don't say that too often but don't listen to that load of bull crap and DO use .env files and DO use them correctly (which can depend on company size but yes, even as multi million dollar comapny and above this is still the right approach!).

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

Please re-read if this is your conclusion.

  1. Git /.gitignore has no correlation to anything I said?? Also, maybe a decade old concept could use an update.
  2. I listed open-source and self hosted options.
  3. Still doesn't address that whenever the .env gets updated, the updater can see EVERY SECRET in the file.
  4. You can't share secrets easily like a config server, which is a url hosted on a VPC.
  5. Google is a multi-billion dollar company and doesn't use .env files?
Collapse
 
tillt profile image
Till
  1. In your first point you rumble on that there is no good location for the .env file since you cannot put it in your repo (structure). If you don't see how this corelates to my statement and thus can be resolved with git ignore/exclude idk how to bring it to you...

  2. And I said "and tools". With those tools you increase your attack surface by miles. And this is not a hypothetical thread. Just look at all the supply chain attacks and other (zero day) vulnerabilities in dev op tools of the last year alone. And for a tool which stores your very soul (secrets) of the whole operation there is simply no good reason to take that risk. You would need to do a 100% code review on every update of this tools and since it is open source you also need to update and that fast since vulnerabilities are also "openly" known. And again for a task as simple as this (just using .env files properly) you go for this risk for no good reason (besides finding the tool flashy or something).

  3. Still you don't seem to even know the concept of pipeline variables (or understand it). In a very basic approach you could have one repo server and multiple build and deploy server which poll the repo. They also hold the secrets. Your devs never get in touch with them and never even know the secrets. The 'updater' (as you call it) of the secrets is the person in charge of that project and he also only has access to the build and deploy server for his products. This is just a very basic example and obviously pipelines in the real world are more complex than that but still very well and very secure doable with just bash and your typical and rock stable unix tools.

  4. So you say a team of somewhat 5 to 20 devs (I rarely have seen more on just one product/scope which shares the same dev secrets - note that they only are dev secrets anyways and it wouldn't be mission critical if they get compromised) cannot share one small text file easily and secure enough? We have come far if the current generation needs a 10k+ loc tool with a flashy name for a task like that...

  5. Than you seem to have more information on that topic than me. Strange though that all their infrastructure and most tools explicitly do support .env files 🤔 And do they just don't use .env files or config files in general? And on all projects or just some? I guess I would need more sources on that one 😆

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited
  1. I don’t know know where to go either with this point.

  2. Nothing is full proof not this site, not hosting your code on GitHub, or deploying on Digital Ocean, GCP, AWS, etc…

  3. So a person seeing all secrets is ok because he is in charge? That does not sit well with me. At Google you can be the VP of a project and you still don’t have clearance to view a secret.

  4. Change takes time, why use anything? Tools are built to make life easier. We don’t need to copy and paste or trust anyone because we have a tool with permissions to do that for us. And it doesn’t matter how many lines of code it has, why is that a metric that need to be brought up?

Collapse
 
dnmeyer06 profile image
Daniel Meyer

AWS Secrets Manager has been incredibly valuable in terms of managing .env file configs for our team. No need to worry that you've got the wrong config, just set up a bash command to pull down the latest from AWS.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

Interesting. I will make some time to investigate these and see if I can integrate support for them into wj-config. Basically create a data source that understands how the server works.

And yes, I agree that dotenv is not the greatest. If it were, I would not have had to make wj-config in the first place.

Collapse
 
gregorygaines profile image
Gregory Gaines

What is the main use-case for wj-config?

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

wj-config is a versatile configuration package that does for JavaScript what Microsoft did for .Net: A hierarchical configuration system composed by multiple configuration data sources. Main use case? Any JavaScript project, basically, that requires configuration that has the concept of environments or similar scenarios, like per-tenant configuration, for instance.

Collapse
 
smpnjn profile image
Johnny Simpson

I don't get it, like I mean .ssh passwords and keys are also stored as files somewhere on your server. Having a .env file in your www folder (or whatever you are using) is not inherently insecure. Obviously if you made it publicly available, it would be. I get that GCP or whatever builds this into vaults and that's great if you're using GCP, and perhaps Google builds in extra security, but there is really nothing inherently wrong with using a .env file.

Collapse
 
slavius profile image
Slavius

My thoughts on this:

To solve including your .env files inside your docker images use volumes. Mount your .env files during deployment not build. That's how Azure DevOps and Kubernetes does this to protect the secrets.

Exposing your database password inside a file is not a big security issue on its own. The DB server (or any other service protected by credentials you use) should not accept connections from untrusted sources by default so even with leaked username/password the only way to get in is to have application execution access or user access to the shell of your application server - and if the attacker has it, it's too late for anything.

How are password servers protected? Again username/password? Where are those stored? It's the same dillema just shifted away behind another SPoF node.

Can you please elaborate how it actually improves anything?

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited
  1. Secrets aren't fully exposed when someone wants to edit a secret. Thats a big plus for me.

  2. Config servers provide an audit trail for who / when secrets where accessed or updated.

  3. Access control and permissions.

  4. Versioning for roll backs or deployment strategies.

  5. Less likely of a human error, like messing up a key-value pair and causing a parsing error.

And yea, almost every problem is just shifted behind another node, but that doesn't mean we can't improve along the way. .env files just seem kinda primitive at this point.

FYI - It doesn't have to stop with simple usernames and passwords; we now have physical keys and biometrics.

Collapse
 
slavius profile image
Slavius

All this is solved by CI/CD servers that store secrets and generate .env files during deployment.
Generated artifacts make it easy to roll back or forward.
They provide interface to securely edit only permitted secrets with audit trail based on user authorization.
There's no need to introduce additional SPoF that can fail and render your application unusable.
Commiting a DDoS attack against config server might be in the end easier than DDoS ing Cloudflare, etc.
Config servers introduce additional unnecessary latency where a read of memory-mapped file with secrets would suffice.

Thread Thread
 
gregorygaines profile image
Gregory Gaines

Config servers are usually hosing on internal VPC to prevent DDoS attacks.

Where would the latency come from when it’s on an internal VPC (a local host type connection).

Even still a major issue still stands, the entire file of secrets is exposed when someone makes an update.

Thread Thread
 
slavius profile image
Slavius

The latency comes from processing on the client and the config server:

DNS resolution + TCP handshake + SSL/TLS key exchange & encryption + HTTP L7 protocol + deserialization & serialization of data + DB query

Then you have the secrets stored in the application memory anyways.

Your application is anyway authorized to read the secrets so they're not secrets anymore. What's the difference to reading them from a file?

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

I don't see a service in a VPC generating a wait time more than a few milliseconds unless there was an issue with the underlying service itself.

Unless you have an application vulnerability, data in application memory is safe, unlike .env. If an attacker gets access to the host machine, then they could just read our the system environment variables for the .env.

Also you gotta remember, environment variables are global to that machine unlike the application runtime.

Collapse
 
lewiscowles1986 profile image
Lewis Cowles

We use .env for local Dev and versioned secrets for prod. I don't know that I've ever seen someone using production.env 🤷‍♂️

Maybe you've had bad luck.

I would warn against coupling local-dev to a config or secrets manager though.

Collapse
 
mrdulin profile image
official_dulin • Edited

If you use k8s, there is another choice.

For configurations - ConfigMap
For secrets - Secrets

However, in order to update the configuration without downtime, you generally have to create your own configuration center and provide API

Collapse
 
alexagc profile image
Alejandro Gomez Canal

Secrets plus external secrets (external-secrets.io/v0.6.0-rc1), perfect combo inside k8s clusters

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Thanks for the article. I have known for a while now not to commit secrets, but I hadn't seen a way to easily keep track of them.

I want to address a couple of niggles I have seen in the discussion:

The phrase is "fool proof", as in protected from fools. However "full proof" is a common eggcorn, so I understand where it comes from.

I have not encountered the phrase "agree to meet in the middle" before, but that could just be my sheltered lifestyle. "Meet in the middle" is used in sentences like "I'm trying really hard here, can you at least meet me in the middle" or "It seems like we can meet in the middle", meaning compromise.

What you seem to be saying is that you want to stop the discussion where it is, so you want to "agree to disagree", because you can't reach a compromise or other agreement, which I suppose is a compromise of sorts!

Collapse
 
gregorygaines profile image
Gregory Gaines

Foolproof? I didn’t even notice, imma have to take that up with my MacBook autocorrect.

Using “meet in the middle” is a habit for me, I never really liked plainly using agree to disagree because we just agree to stop the argument there which seems a little shallow.

I liked the phrase because to me it insinuates we take the time to understand the other person then once we meet at the disconnect then we agree to disagree.

That’s just how I see it. Maybe I should switch back, might cause less confusion.

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Yeah, autocorrect can be very frustrating!

No need to switch! I saw an interaction with another user and mistook your question about their interpretation of the phrase to mean you thought it was a well known idiom. My mistake.

 
gregorygaines profile image
Gregory Gaines

I know I'm bias but I like your take 😂.

I share some of the blame, I should have been clearer in the article. Also, I should have taken into account that not everyone has tons of experience in the cloud space or the experience of working on huge enterprise projects. Especially when devs are saying things like "we have 2 trusted devs" so he can view the secrets.

Collapse
 
delamux profile image
Luis del Amo

Hahahahaha. I love this 🔥🔥🔥🔥🧯🧯🧯🧯 kind of articles. I just only can tell, I didn’t have any problem with .env files in my life. But is true that the cloud system. Looks better in terms of maintainability.

But the title was perfect to have some enemies.🤣🤣🤣🤣🤣

Collapse
 
vergil333 profile image
Martin Machava

For the same reason as you, I’m not using dotenv. I’m storing all my secrets in environment variables and those are loaded on start time or compile time.

On AWS it works both for react (stored in pipeline) and spring (in config of EB).

I didn’t know about AWS Parameter Store, thanks for the tip.

Collapse
 
collimarco profile image
Marco Colli

Aren't those services the main target for hackers? A single bug could expose information for millions of companies and secrets...

Or is there a master password that is not stored on those services? But then again, you would have to keep this local secret secure...

Collapse
 
gregorygaines profile image
Gregory Gaines

Hey Marco, can you elaborate on what you're trying to say?

Collapse
 
collimarco profile image
Marco Colli

Are passwords encrypted end-to-end on those services? Or, in case of a data breach, the hackers can read all the passwords?

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

If self hosted, config servers are usually hosted on VPC's.

You can check the documentation for cloud services, for ex. Google Secret Manager.

Data is encrypted in transit with TLS and at rest with AES-256-bit encryption keys.

They also allow you to access the service behind a VPC.

VPC Service Controls support

Collapse
 
randomblock1 profile image
Benjamin G.

Don't forget Doppler. It's free and lets you have multiple environments.

Collapse
 
dubcee93 profile image
dubcee93

I don't think I'll be getting in on this heated discussion myself - but I just wanted to say that I enjoyed the article. It was well thought out and reasoned and good examples were provided. I found it interesting. I also found the comments interesting and you have done a good job rebutting most peoples claims that you are wrong. I tend to agree with you (but I am newer to actual software engineering, have spent many years as a cloud (Azure) architect, though). Anyways, thanks for the post and please keep them coming!

Collapse
 
gregorygaines profile image
Gregory Gaines

Thanks, I really wanted to teach others another practice.

Don't hesitate please give your side. This is probably the most fun I've had on a forum site where people actually give opinions instead of being hive minded like on reddit or stackoverflow.

Collapse
 
gregorygaines profile image
Gregory Gaines

I was really confused about the person complaining about an SDK side. It's just a wrapper over a web API not the development kit for an Xbox.

With you approach I like that you can detect errors immediately, not waiting for the CI/CD pipeline to success just to start your app and realize something failed then having to re-run the pipeline again.

With a config server, you could update the relevant configs and just restart the server.

I don't get the obsession of "i could write it myself". You don't agree with me because you can write all the features yourself? I hope they realize once they write all those features they built a config server and did a complete circle 🤣.

Collapse
 
zodman profile image
Andres 🐍 in 🇨🇦

supabase has the password manager :)

Collapse
 
gregorygaines profile image
Gregory Gaines

Mind passing a link, would love to read its docs.

Collapse
 
zodman profile image
Andres 🐍 in 🇨🇦
Collapse
 
jordancalhoun profile image
Jordan Calhoun

Super good to know. I love the versioning baked into the URLs

Collapse
 
gregorygaines profile image
Gregory Gaines

Yea, makes it super easy to keep a paper trail of secrets / configs.

Collapse
 
captaint33mo profile image
Vibhor Sharma

Good concise article with pros and cons listed nicely. I didn't knew any service like that existed (or maybe i was living under a rock all these years while working on different projects lol). Will definitely give it a try in my next project.

Although the main takeaway from this is that its totally upto the size of your projects and what method you choose. But it's good to have different options to use secrets in your projects securely.

Collapse
 
davestewart profile image
Dave Stewart

I tell you what, keeping env files across multiple environments is a pain in the ass!

If that vault tool can help with that, I'm all for it

Collapse
 
acarrasco profile image
Alfonso Carrasco

Muchas felicidades por tu articulo, yo considero que es una buena opción, generalmente para llegar a la misma meta, puedes elegir diferentes caminos. Personalmente creo que es un buen articulo y estaría encantado de ver un video explicando el funcionamiento en un proyecto básico.

Felicidades y saludos desde México 🌮

Collapse
 
dalcio profile image
Dalcio • Edited

We must know that we can't control everything and some times we must trust even if we won't in other peoples.
So what I means is that if we don't trust why we should host our project in the cloud by starting, why we use cloud services for our projects?

Thanks for this article. I'm gonna follow this article

Collapse
 
madza profile image
Madza

great writeup 👍✨💯

Collapse
 
gregorygaines profile image
Gregory Gaines

Thanks Madza! I enjoy all your articles, you write nothing but bangers!!

Collapse
 
gnogueira profile image
Gustavo Nogueira

Finally an interesting comment section with mostly devs arguments/discussions!

Collapse
 
gregorygaines profile image
Gregory Gaines

This ^.

Collapse
 
fluffynuts profile image
Davyd McColl

From your description, I think you've seen some bad practices, so here goes:

  1. the .env file should never be committed to the repo -- it should be in your .gitignore!
  2. there are supplementary files which you can commit to use in dev, eg .env.development or .env.example which could be used to set up a dev environment. .env.example would contain a bunch of lines like VARIABLE= with no value set, so that a dev could copy that to .env locally and set the appropriate values.
  3. you don't need .env in your docker container - the whole point is that these files specify environment variables, if they aren't already set. In other words, your prod runtime could just have these variables set by the launcher somewhere (eg via config in your deployment tool (we use Octopus) which is spat out somewhere.
  4. if any of these values are defined via environment variables, those environment variables take precedence, so another way to have this config opaque is to have it defined as part of env vars for the user running the process.

I don't have a problem with config servers, just that I think if you'd seen good practices upheld with .env files, you may not fear them as much.

Collapse
 
twysto profile image
TwystO • Edited

Exactly the response I was about to write, you saved me some time bro!
Never commit your .env (.env with secrets inside should be in you .gitignore) but commit a .env.example with empty values.

Collapse
 
samuelrivaldo profile image
Samuelrivaldo

Thanks you 🙏

Collapse
 
bvallelunga profile image
Brian Vallelunga

I am clearly biased but I'd recommend taking a look at Doppler: doppler.com

Collapse
 
jameslovallo profile image
James Lovallo

I just store my secrets in Netlify and use them with ntl dev. Problem solved.

Collapse
 
seancassiere profile image
Sean Cassiere

Thanks for the article 🙌🏼

 
smpnjn profile image
Johnny Simpson

Well yes security is a spectrum right. There is nothing "wrong" with doing these things, but different organisations have different risk tolerances. For orgs with lots of failure points (see: lots of people), you may want to avoid these things for reasons you listed. But for single developers or people aware of those risks this would work fine. I just think a sweeping statement like "stop using .env files" really raises the barrier to entry for people getting started on sites like these, and with little justification I find this article to be a bit clickbaity.

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

Funny you should say that because I set the experience level for the post to the highest I could to avoid that very issue. Either DEV needs higher levels or some people are lying about how much experience they have. Joking aside.

Little justification for entry level people who haven't encountered these issues, but big improvements for large projects with experienced devs who understand the issues and how this could improve their process.

Collapse
 
codypotter profile image
Cody Potter

I only use .env files in a vs code dev container just to hydrate a local dev environment. REAL secrets belong in AWS secrets manager or some config service like you mention.

Collapse
 
katya_pavlopoulos profile image
Katya Pavlopoulos

Very insightful, the versioning complications didn't even occur to me. Thank you Gregory

 
gregorygaines profile image
Gregory Gaines

I haven't been following this thread. I think your comments where important for showing a different point of view. If you could, I think it would be better if you restored it.

Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀

I'm a moderator here and even I don't have the power to restore comments.
To sum it up, I don't agree, I won't have words pit in my mouth, I have to put my son to bed and I don't care about this, more notifications please 😔

Collapse
 
niros profile image
Nir Levy

Great article. I also suggest using doppler

Collapse
 
gregorygaines profile image
Gregory Gaines

Lol I should, but I don't want to seem pretentious, thats why I didn't detail my work experience.

Collapse
 
collimarco profile image
Marco Colli

It seems a little arrogant from you to say something like this, I would be curious to compare the CVs.

In any case if I'm wrong with my assumption you can just explain why I am wrong and what I am missing. That would be much more useful and interesting. If you don't give any explanation and just offend other's opinions, that is not constructive behavior.

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 🫰

Collapse
 
gregorygaines profile image
Gregory Gaines

Thanks!!

Collapse
 
miboch profile image
Mikkel Christensen

This article is lacking in nuance. If people have access to your local configuration files they already have access to your system.

Outsourcing trust to some third-party company doesn't make my work more secure. It just makes my operations more convoluted and expensive.

Whoever updates the .env will have access to every secret in the file

As opposed to an unknown number of people having access to everything via a third party hosted service.

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

There are self-hosted options that mitigate that risk.

I mean you trust a third-party company to host your code, sites, passwords like Github, Gitlab, AWS, Digital Ocean.

If thats an issue why use anything?

Collapse
 
miboch profile image
Mikkel Christensen

If thats an issue why use anything?

The fewer third parties I have to involve the better in my estimation.

Self-Hosted is a good option, but its more work maintaining the infrastructure which makes it non-trivial for small projects.

My primary contention with your article is that it espouses config servers as a blanket solution disregarding nuance in all other aspects.

I'm not a proponent of .env files, but I do not believe in over-applying general advice.

Thread Thread
 
gregorygaines profile image
Gregory Gaines • Edited

I’m pretty sure the options can be weighed. I don’t expect someone’s personal blog to have a whole config server but I do expect it from a company that brings in revenue and holds customer data, can never be too safe for your users.

I don’t think it’s a good look to argue against using a more secure practice. How does that look to consumers?

Collapse
 
sabberubbish profile image
SabbeRubbish

Don't forget Azure KeyVault

Collapse
 
georgewl profile image
George WL

That just creates a whole swaith of new issues no?

Like not being about to run any of the app if the config server can't be connected to, for any of myriad reasons.

Collapse
 
theaccordance profile image
Joe Mainwaring

I don't see .env files going anywhere

While yes, there are definitely better approaches for deployment scenarios to store and pass your secrets, it's still the most effective way to define them for feature development locally.

One thing I've done with my org to help improve the workflows around this file is to leverage 1Password. I'm able to create a .env-template file with reference pointers instead of values, and the 1Password CLI will generate a .env file using the template and fetching the values from my vaults stored in the 1Password cloud. I've written about how to do that here.

Collapse
 
smpnjn profile image
Johnny Simpson

What? Storing .ssh keys in the .ssh folder is literally how ssh works..

Collapse
 
roestvrijstaal profile image
RoestVrijStaal • Edited

yourlogicalfallacyis.com/appeal-to...

Because anyone could claim to work at Google or another Big Tech company without a proper LinkedIn link or reference to a "Our Team" / "About us"-page with their name & profile photo.

Also, how does the app know which URL to call to to get the credentials?
How does the credential server know the request for credentials comes from a valid app?

Hardcoded URL? Hardcoded app-identifier?
Ewwww. A text file which could be edited without the need of a developer would be more fitting. Let's name it .env and put a symlink to it in the main root of the project.
....Wait, what?

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

Personally you don’t have to believe where I work but if you need to know here’s my GitHub where you can see that I’m part of the Google org. But let's ignore that, there are way better talking points than my employment.

Your app connects using a VPC which is pretty much a local host like connection. You can hardcode this url not like it’s gonna change much.

Orrr wait let’s think outside the box, instead maybe you could define the url as a constant? Lol no text file needed.

Collapse
 
mnlwldr profile image
manuel

Config servers to the rescue

So that means you have an .env file for the config server in your application with all the secrets to your config server and everyone who has access to the .env file has access to all configurations.

Collapse
 
gregorygaines profile image
Gregory Gaines

No. There are no .env files involved.

Collapse
 
mnlwldr profile image
manuel

How the application know about the config server?
What about different config server for different environments?
What about credentials?

Thread Thread
 
gregorygaines profile image
Gregory Gaines

How the application know about the config server?
By the endpoint you pass to it.

What about different config server for different environments?
You will use one config server, it will probably have a way to define different environments.

What about credentials?
If you are using cloud hosting, then the application itself would have creds in its environment.

Collapse
 
teamradhq profile image
teamradhq

Or even better than added yet another layer of complexity, do the opposite: Commit all of your .env file to your repos. This way, everyone on the team has access to them, so there's no need for a credentials manager, no need to connect to a remote machine to update its configuration, and 100% guarantee that everyone has the same local environment configurations available.

The simple fact is that if your system enables an unprivileged user to access machines in your private network and connect to any containers they're running, you've already failed.

Having a database username, host and password should not be sufficient information for an unauthorised actor to compromise your systems.

If they are, you're doing it wrong and you've already been compromised.

 
Sloan, the sloth mascot
Comment deleted
Collapse
 
tforster profile image
Troy Forster

Stop Using .env Files For Secrets Now!

There, I fixed it for you. ;)

Joking aside, your points are valid for secret storage. .env variables can leak into exception messages echoed to the client and be captured into log files too.

However, .env files are great for non-secret configuration. Especially for customising Dev environments such as which port to expose a test server on. If the .env file is gitignored then each developer can tweak non-production-affecting params and not worry about overwriting each other on merge.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
ltsochevdev profile image
Sk1ppeR

.env in production is dumb I agree. But for localhost it's fine. I disagree that you necessarily need a config server or that you need to cough money to FAANG(bezos in particular) to feel secure. Env is simply a cover for an archaic functionality, wait for it, yes I'm talking about system environment variables. They are perfectly fine in production. Why do you ask? Well if someone breaches your server you are pretty much a goner as far as secrets go. Secondly, a lot of frameworks integrate the secrets in the final bundle during build time (NextJS server side is one example) and honestly using a config server there is just as dumb as relying to .env file.

Collapse
 
gregorygaines profile image
Gregory Gaines

You are right using a config server during build time would be dumb, thats why its not. Your server reads from a config server on startup.

Collapse
 
adamedwards profile image
Adam

You make a great point because in AWS permissions can't be wrong. 0600 is really hard to get right, but IAM policy docs are super straightforward.

Collapse
 
thomasjunkos profile image
Thomas Junkツ • Edited

First of all: This is really good advice! And I find it good when Googlers take the opportunity to help spreading good practises.

But ...
it is muddied behind bad communication skills.

I think if you dial down the paternalistic tone a bit it would not make you sound like you are selling snake oil.

There are simple scenarios where a .env file may be okay and a centralized solution might be a bit over the top. And there are many scenarios where this may be the appropriate solution but people do not use it for whatever reason.

If your intention is really to help people you may want to hold back a bit of your ego which may turn people off from evaluating your idea and instead evaluate you. That is countrary to your intention.

Collapse
 
gregorygaines profile image
Gregory Gaines

Thanks for the criticism, a lot of people took this as a personal attack which was not my intention.

 
adamedwards profile image
Adam

Lol I was just messing around. You're right though. There's definitely not a way to audit syscalls about file and attribute operations and send those to a SIEM and alert on them. And even if that existed it's not like it's best practice to monitor those things anyway. So yeah I'm in your camp on this one.

Collapse
 
teq3 profile image
Take 3 on tech

One thing I don't see you address is performance. Maybe you can make a point for secrets but then you mix configuration with secrets.

Should we have to pay the price of a round trip to the configuration server every time you need a certain configuration value? This is madness! 😜

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

Not if your config server is hosted on a VPC (ex. Google Secret Manager or your self-hosted). An application, it only needs config vars on startup, so a quick fetch isn't going to affect performance. If it does, then the config server is not your issue.

Additionally, since config variables are fetched on startup, you can freely update config variables knowing your service will always get the latests version.

Madness sold separately. 😜

Collapse
 
oz profile image
Evgeniy OZ

What a crazy bullshit. .env files should not be in repo, they should be in .gitignore - that’s it, problem solved. You can generate .env in CI before execution.

Collapse
 
gregorygaines profile image
Gregory Gaines • Edited

An interesting conclusion. It might be worth taking a second thorough reading if this is what you got.

  1. You don't address that whenever the .env gets updated, the updater can see EVERY SECRET in the file.
  2. You can't share secrets easily like a config server, which is a url hosted on a VPC.
Collapse
 
oz profile image
Evgeniy OZ

If your IDE has access to a config server URL, then you have access to the same URL.

Thread Thread
 
gregorygaines profile image
Gregory Gaines

I’m not sure what this is supposed to mean.

Ideally, config server can only be access from a VPC or from users / applications you approve.

I guess If you IDE can access the url if you are allow listed? Does that cover what you are saying?

Collapse
 
adzetko profile image
Maxim "Adzy" Hohengarten

For me there's a point missing in this article, how is this more secure than an .env file? I'm not that much into security and that's why I read that article, how does it work? How can I be sure the URL is only accessible to the authorized entry points?

Collapse
 
gregorygaines profile image
Gregory Gaines

Hello Maxim, can you take a quick re-read of the article. Usually, confg servers are accessed from VPCs.

Collapse
 
wadecodez profile image
Wade Zimmerman

Posting the same thing as I did on the rebuttal...

Definitely a bigger fan of .env, but don't really enjoy either article because I think this is a stupid debate.

IMO do whatever is more efficient for your team. If there is actually a benefit to using the cloud vs .env files then use the cloud.

However, on my "small scale" projects, the time/costs required to implement a config server are not worth it. For me, it is more efficient to use a .env file.

 
ravavyr profile image
Ravavyr

Look, i can't help you see the reason this entire argument is pointless.
Suffice it to say that all security measures are flawed because they are implemented by human beings and have to be maintained by human beings.
What does hurt projects often [that i've experienced with at least half a dozen clients] is being overly paranoid and trying to secure everything to the point where basic assets are not accessible and sites go down when they shouldn't. At that point it's hurting more than it's helping. And having a .ENV file in 16 years has not once been the problem. So per my experience, it's not an issue. You claim otherwise, and as everything in this industry, we can leave it to personal preference.

Collapse
 
brunofin profile image
Bruno Finger

We use a .env-example file that contains env values to be used only on a local development environment or simply empty values for sake of documenting them.

On a production environment such as Azure, AWS, Vercel or really any other, the env variables are defined in the environment build settings passed down as system environments variables not as a file. The .env file is simply a standard way for a program to read local environments variables, and technically speaking it is not able to distinguish whether those values come from a system env or a local .env file.

And this is where the premise of your article breaks. If you assume storing environment values in a VCS file is the correct way of using those then you already started wrong.

But nothing wrong in using a .env file. As long as you do it correctly.

Collapse
 
petezahad profile image
Mathias Stocker • Edited

The idea of having an .env file in a repo is to have a TEMPLATE of the needed ENVironment variables as documentation which variables need to be set. They could have default values but as we all know they should never contain real username and passwords.

The application (or deployment workflow) should then load this template .env and look in other places to override this default values depending on the current environment. This could be a .env.local file on the system, already set system environment variables or variables from a config storage.

The point is don't stop using .env variables to document which variables need to be set/cared about on the system where the application runs

Collapse
 
tasin5541 profile image
Miftaul Mannan

The title might mislead beginners who are working on a Frontend project.

If you're on a Frontend project (React, Angular etc), I'd say keep using env variables to store simple configs based on dev/prod/sit environments (api url, or other non secret configs). Since most of the react projects are rendered on client side, there's no need to overcomplicate things.

BUT, if you need to access secrets, then you MUST store them in a key vault and access them from backend with managed/system assigned Identity, do whatever you need to do with those secrets and pass the data back to frontend. NEVER pass the secrets to frontend. You can't access values from key vault from frontend anyway because those key vaults restrict your access.

Collapse
 
sebconejo profile image
Sébastien Conejo • Edited

Sometimes, you have to get some difference. For example, when you send automatically an email each month, or depending on any event, you have to run a different setup on dev mode to run tests, to try several emails during the next hour, seeing your email directly on the console. Another example, you could need to call another api on dev mode than on prod...

Collapse
 
treckstar profile image
Brandon Trecki

Definitely some good points.

I've seen so many people forget a simple and extremely important security tip:
cycling keys and secrets after an employee has left/no longer works for the company.
Making a process to re-create secrets and keys every so often is important.
⤜(ⱺ ʖ̯ⱺ)⤏
So what's worse: plain text password storage in 2022 or overused secrets and keys?

Image description

Collapse
 
vinceamstoutz profile image
Vincent Amstoutz

An amazing git-based resource to control that your secrets are not exposed in the codebase is GitGuardian ! With this tool you can also check if there is a secret in the pre-commit event thanks to git hooks .

Collapse
 
vinceamstoutz profile image
Vincent Amstoutz • Edited

An amazing git-based resource to control that your secrets are not exposed in the codebase is GitGuardian! With this tool you can also check if there is a secret in the pre-commit event thanks to git hooks.

 
ravavyr profile image
Ravavyr

lol

  1. 500 errors only happen if you wrote bad code or didn't debug it enough. This is fact. I fully expect 500 errors if i forget to setup the correct configs in the .env file. You're supposed to fix those across your application and account for any combination of them and make sure to log them and keep an eye on those logs for new ones and then fixing them.

  2. note, my habits extend 16 years, which means i've been coding since before env files existed and i still run some older monolith systems while also keeping up with various frameworks, platforms, services, tools and whatever else people keep coming up with. Config files only get scanned automatically if you don't secure the damn things which again shows that maybe you just lack experience in the field. Credential sharing happens yes, and it's just as bad as not securing your env file from external access, but so is clicking on a bad link in an email, or not setting folder permissions correctly, or a mountain of other issues. ENV files are not the problem, nor were they ever.

Collapse
 
ravavyr profile image
Ravavyr

Has it happened? yes
Does it happen? yes
Is the problem having environment files with credentials? no

The problem is always people setting those files up wrong, and not securing them adequately.

That's literally where i was going with my original comment and everyone on here decided i was saying "we should all willy nilly throw env files everywhere! woooo!!!!"

I've got 16 years experience, worked on over 400 different customer sites/applications. Trust me, i've seen plenty of hacked systems, broken systems, badly programmed systems and well frankly there is no system that doesn't have holes, they don't exist. Oh and corporations are the worst, no one takes responsibility for anything and no one knows anything further than the tip of their own nose, which is often why different tools and systems conflict or rules in one place cause something in another place to break. I see that last part damn near every day, so when it comes to the credentials being the problem, that's the problem maybe 0.1% of the time. 90% of the time it's some non-tech person edited something they shouldn't have and broke it. the other 9.9% are the myriad of infinitely complex complications that may or may not happen at any given time. :)

Collapse
 
xgenvn profile image
Brian Ng

There is missing important piece, is to clarify which is a secret, which is config. I can see everyone using .env for everything, but we should start thinking about separation of those.

For config, it's easier to manage and put in the source code directly. The versioning will go long with the release we make. Not necessary to have versioning from mentioned secret stores.

For secrets, it's also possible to manage by Git itself plus some secret tools like SOPS, git-crypt, git-secret,...

For certain service, the normal secret model need to be enhanced. When applying secret stores, or .env, it can be dumped from the process (talking about which layer being exposed). So there are tools (eg: berglas for example), which help us to maintain this. But comes with trade-off, that means more calls to external source.