Amir Sharif
Engineer.
Weekend hacker.
Self improvement enthusiast.

Allowing AI editing of Rails credentials

When working with AI coding agents, one of the things that they can’t do very well is interactively use the shell.

A common problem is add/removing keys in the Rails credentials files, since it typically involves opening an editor.

I added a small script to bin/rails-credentials to help with that. It’s used like this:

bin/rails-credentials add environment key value
bin/rails-credentials remove environment key 

The code for it is below:

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

require 'pathname'
require 'fileutils'
require 'optparse'

# Setup Rails environment
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup'

require_relative '../config/boot'
require_relative '../config/environment'

# Parse options
options = { overwrite: false }
OptionParser
  .new do |opts|
    opts.banner =
      'Usage: bin/rails-credentials COMMAND ENVIRONMENT KEY [VALUE] [OPTIONS]'
    opts.separator ''
    opts.separator 'Commands:'
    opts.separator '  add       Add or update a credential'
    opts.separator '  remove    Remove a credential'
    opts.separator ''
    opts.separator 'Examples:'
    opts.separator '  bin/rails-credentials add development linkedin_api_key xxxx1234xxxx'
    opts.separator '  bin/rails-credentials add production stripe_secret_key sk_live_xxx --overwrite'
    opts.separator '  bin/rails-credentials remove development test_api_key'
    opts.separator ''
    opts.separator 'Options:'

    opts.on(
      '--overwrite',
      'Overwrite the key if it already exists (only for add command)',
    ) { options[:overwrite] = true }

    opts.on('-h', '--help', 'Show this help message') do
      puts opts
      exit
    end
  end
  .parse!

# Parse positional arguments
if ARGV.length < 2
  puts 'Error: Not enough arguments'
  puts ''
  puts 'Run with --help for usage information'
  exit 1
end

command = ARGV[0]
env = ARGV[1]
key_name = ARGV[2]
key_value = ARGV[3]

# Validate command
valid_commands = %w[add remove]
unless valid_commands.include?(command)
  puts "Error: Invalid command '#{command}'"
  puts "Supported commands: #{valid_commands.join(', ')}"
  puts ''
  puts 'Run with --help for usage information'
  exit 1
end

# Validate argument count based on command
if command == 'add' && ARGV.length < 4
  puts "Error: 'add' command requires 4 arguments: add <env> <key-name> <key-value>"
  exit 1
elsif command == 'remove' && ARGV.length < 3
  puts "Error: 'remove' command requires 3 arguments: remove <env> <key-name>"
  exit 1
end

overwrite = options[:overwrite]

# Validate environment
valid_envs = %w[development production test staging]
unless valid_envs.include?(env)
  puts "Error: Invalid environment '#{env}'"
  puts "Supported environments: #{valid_envs.join(', ')}"
  exit 1
end

# Determine paths based on environment
if env == 'development'
  # Development uses the default credentials file
  key_path = Rails.root.join('config', 'master.key')
  credentials_path = Rails.root.join('config', 'credentials.yml.enc')
else
  # Other environments use environment-specific credentials
  key_path = Rails.root.join('config', 'credentials', "#{env}.key")
  credentials_path = Rails.root.join('config', 'credentials', "#{env}.yml.enc")
end

# Check if key file exists
unless File.exist?(key_path)
  puts "Error: Key file not found at #{key_path}"
  puts ''
  puts "To create credentials for #{env}, run:"
  if env == 'development'
    puts '  EDITOR=nano rails credentials:edit'
  else
    puts "  EDITOR=nano rails credentials:edit --environment #{env}"
  end
  exit 1
end

begin
  # Load or initialize credentials
  credentials =
    ActiveSupport::EncryptedConfiguration.new(
      config_path: credentials_path,
      key_path: key_path,
      env_key: 'RAILS_MASTER_KEY',
      raise_if_missing_key: true,
    )

  # Read current credentials
  current_data = credentials.read
  current_data = current_data.blank? ? {} : YAML.safe_load(current_data) || {}

  case command
  when 'add'
    # Check if key already exists
    if current_data.key?(key_name) || current_data.key?(key_name.to_sym)
      unless overwrite
        puts "Error: Key '#{key_name}' already exists in #{env} credentials"
        puts 'Use --overwrite flag to overwrite the existing value'
        exit 1
      end
    end

    # Add/update the key-value pair
    current_data[key_name] = key_value

    # Write back to encrypted file
    credentials.write(current_data.deep_stringify_keys.to_yaml)

    puts "✓ Successfully added '#{key_name}' to #{env} credentials"
    puts ''
    puts 'You can now access it in your Rails app with:'
    puts "  Rails.application.credentials.#{key_name}"
  when 'remove'
    # Check if key exists
    unless current_data.key?(key_name) || current_data.key?(key_name.to_sym)
      puts "Error: Key '#{key_name}' not found in #{env} credentials"
      exit 1
    end

    # Remove the key (handle both string and symbol keys)
    current_data.delete(key_name)
    current_data.delete(key_name.to_sym)

    # Write back to encrypted file
    credentials.write(current_data.deep_stringify_keys.to_yaml)

    puts "✓ Successfully removed '#{key_name}' from #{env} credentials"
  end

  puts ''
  puts "Credentials file: #{credentials_path}"
rescue => e
  puts "Error: #{e.message}"
  puts e.backtrace.first(5).join("\n")
  exit 1
end

Date
October 12, 2025