DEV Community

Bradford Fults
Bradford Fults Subscriber

Posted on

Copy Config Vars from One Heroku App to Another

Below is a quick little script I threw together to copy config vars from one Heroku app to another, e.g. when trying to create a staging or test app that [largely] mirrors another.

It relies on a Heroku app.json to specify which config vars are required, combined with a dump of your other app’s config vars via heroku config --shell -a <app-name> >foo.env to get the <env-file> input.

#!/usr/bin/env ruby
# frozen_string_literal: true

require 'json'

# Usage: env-setter <app.json> <env-file> [-a <heroku-app-name>]

app_json_file   = ARGV[0]
env_file        = ARGV[1]
env_var_keys    = []
heroku_app_name = nil

# parse command line -a switch to get Heroku app name
if ARGV.include?('-a')
  heroku_app_name = ARGV[ARGV.index('-a') + 1]
end

# Pull required config vars from app.json
begin
  parsed_json = JSON.parse(File.read(app_json_file))
  env_var_keys = parsed_json['env'].map {|k,v| k if v.is_a?(Hash) && v['required'] }.compact
rescue JSON::ParserError, EOFError
  puts "Error parsing JSON file: #{app_json_file}"
  exit 1
end
# puts "Required config vars from app.json: #{env_var_keys.join(', ')}"

# Pull env vars from env file
begin
  env_vars = Hash[*File.readlines(env_file).map(&:chomp).map { |line| line.split('=', 2) }.flatten]
rescue EOFError
  puts "Error reading env file: #{env_file}"
  exit 1
end
# puts "Loaded env var names from #{env_file}: #{env_vars.keys.join(', ')}"

# Check if any required env vars are missing
missing_vars = env_var_keys - env_vars.keys
if missing_vars.any?
  puts "Missing required env vars from #{env_file}: #{missing_vars.join(', ')}"
  exit 1
end

# Set config vars on Heroku if app name provided
if heroku_app_name
  puts "Setting config vars on Heroku app #{heroku_app_name}..."
  system('heroku', 'config:set', '--app', heroku_app_name, *env_vars.map {|k,v| "#{k}=#{v}" }.flatten)
end
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs