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:

#!/bin/bash

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
development:
  secret_key_base: ${KEY_DEV}

test:
  secret_key_ba se: ${KEY_TEST}

production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
EOL
fi

It will generate a file like this:

development:
  secret_key_base: ccfbe0e981877fdf63875565...

test:
  secret_key_base: b01fece76bfdfa613fc19ae4...

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

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

gem share .gem