IRB Rocks!

# Hack your code

Create a secrets.yml file dynamically with bash

Post image

Every Rails application needs its own secrets.yml file to work. When you distribute an application, you have two options to deal with this file:

  • To keep it in the repository and share the development and test key with other users. If you share your production key a kitty will die 😢.
  • To include a secrets.example.yml file and force the user to copy it and generate the secret tokens.

However, in projects I use docker, I want the user only should run docker-compose up -d to setup the environment. In this case, I can use the first approach and keep the file in the repository.

I think there is a better choice, and it's to generate that file on the first boot dynamically. I've created a simple bash script to create a new secrets.yml for every user. You only need to add it in your entrypoint script:


if [ ! -f ./config/secrets.yml ]; then
  echo -e "\nGenerating a secrets.yml file"

  # Random Keys
  KEY_DEV=$(bin/rake secret)
  KEY_TEST=$(bin/rake secret)

  # Generate the file
  cat > ./config/secrets.yml <<EOL
  secret_key_base: ${KEY_DEV}

  secret_key_ba se: ${KEY_TEST}

  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

It will generate a file like this:

  secret_key_base: ccfbe0e981877fdf63875565...

  secret_key_base: b01fece76bfdfa613fc19ae4...

  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

Check my Docker + Rails5 API + React + Redux boilerplate for a real example.

gem share .gem