Site icon UnderConstructionPage

How to pass environmental variables in envconsul config file?

no code

Working with envconsul can be tricky at first. But don’t worry! This guide will show you how to pass environmental variables in your envconsul config file in a quick and simple way.

What is Envconsul?

Envconsul is a tool that helps you inject environment variables directly into your applications from Consul. This is useful when you want to manage configurations dynamically without changing your application code.

Why Use Envconsul?

There are many reasons why Envconsul is useful:

Setting Up an Envconsul Config File

An envconsul config file is written in JSON or HCL format. It tells envconsul which keys to fetch from Consul and how to pass them as environment variables.

Basic JSON Config Example

This is what a basic envconsul config file looks like:

{
  "consul": {
    "addr": "127.0.0.1:8500"
  },
  "vault": {
    "enabled": false
  },
  "prefix": "app/config",
  "command": ["/bin/bash"]
}

Here’s what’s happening:

Passing Environmental Variables

Now, let’s see how to load these values as environment variables.

Using Key Mapping

By default, Envconsul loads everything under the specified prefix.

{
  "prefix": "app/config",
  "env": [
    "DB_HOST",
    "DB_PORT"
  ]
}

In this case:

Neat, right?

Using Prefixes for Organization

If you don’t want to type each key manually, you can load everything under a prefix automatically.

{
  "prefix": "app/config",
  "clean_env": true
}

With clean_env: true, all keys under app/config are loaded as environment variables.

Using Envconsul in a Docker Container

Running Envconsul inside Docker? No problem! You just need to mount the config file and pass it as an argument.

docker run --rm \
  -v $(pwd)/envconsul-config.json:/etc/envconsul/config.json \
  hashicorp/envconsul \
  -config /etc/envconsul/config.json

This will run Envconsul, fetch values from Consul, and pass them as environment variables.

Conclusion

Passing environmental variables in envconsul is simple once you get the hang of it. Just:

Happy coding! 🚀

Exit mobile version