Copy Config Vars from One Heroku App to Another

h3h

Bradford Fults

Posted on September 17, 2024

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
💖 💪 🙅 🚩
h3h
Bradford Fults

Posted on September 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related