Last active
February 26, 2019 09:22
-
-
Save jaysonsantos/3ef2a7af0fddcec1bed81cecd20a1ef1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'pathname' | |
class EnvImporter | |
def initialize(env_file, environment_name, app_name, overwrite = false, | |
number_of_threads = 4) | |
validate_aws_cli | |
@env_file = env_file | |
@environment_name = environment_name | |
@app_name = app_name | |
@overwrite = overwrite | |
@jobs = Queue.new | |
@lock = Mutex.new | |
@processed_keys = 0 | |
@number_of_threads = number_of_threads | |
@threads = initialize_threads | |
end | |
def process | |
lines = read_file | |
File.open('env.clean', 'w') do |f| | |
lines.each do |key, value| | |
key = key.split('/').last.upcase | |
f.write "#{key}=#{value}\n" | |
end | |
end | |
# exit 1 | |
@total_lines = lines.count | |
lines.each do |data| | |
@jobs << data | |
end | |
schedule_threads_stop | |
@threads.each(&:join) | |
end | |
protected | |
def validate_aws_cli | |
file_path = aws_cli_file | |
exit_with_error unless file_path.exist? | |
content = file_path.open.read.tr(' ', '') | |
exit_with_error unless /^cli_follow_urlparam=false/ =~ content | |
end | |
def exit_with_error | |
puts "The file ~/.aws/config must be present and must include this:\n\n" | |
puts '[default]' | |
puts 'cli_follow_urlparam = false' | |
exit(1) | |
end | |
def aws_cli_file | |
Pathname.new File.expand_path('~/.aws/config') | |
end | |
def initialize_threads | |
Array.new(@number_of_threads) do | |
Thread.new(&method(:process_queue)) | |
end | |
end | |
def process_queue | |
loop do | |
(key, value) = @jobs.pop | |
break if key == :break | |
puts `aws ssm put-parameter --name #{key} --value '#{value}' \ | |
--type SecureString #{'--overwrite' if @overwrite}` | |
increment_counter | |
end | |
end | |
def increment_counter | |
@lock.lock | |
@processed_keys += 1 | |
puts "Processed #{@processed_keys}/#{@total_lines}" | |
@lock.unlock | |
end | |
def read_file | |
IO | |
.read(@env_file) | |
.each_line | |
.reject { |line| line.strip.empty? || line.start_with?('#') } | |
.select { |line| line.include? '=' } | |
.map { |line| line.strip.split '=' } | |
.map { |(key, value)| [format_key(key), clean_value(value)] } | |
end | |
def schedule_threads_stop | |
@threads.count.times do | |
@jobs << [:break, nil] | |
end | |
end | |
def clean_value(value) | |
value.strip.tr('""', '').tr("''", '') | |
end | |
def format_key(key) | |
"/#{@environment_name}/#{@app_name}/#{key.strip.downcase}" | |
end | |
end | |
importer = EnvImporter.new '.env', 'staging', 'app_name', true | |
importer.process |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment