Skip to content

Instantly share code, notes, and snippets.

@manveru
Created September 14, 2018 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manveru/e8687e001e32614847d7d20b5b06c7fa to your computer and use it in GitHub Desktop.
Save manveru/e8687e001e32614847d7d20b5b06c7fa to your computer and use it in GitHub Desktop.
Simple nixos-rebuild deployments
require "file_utils"
class Ops
property hosts : Array(String)
def initialize(host : String)
@hosts = [host]
end
HOSTS = Dir["box_*.nix"].map { |h| h[/^box_(.*)\.nix$/, 1] }
def initialize(host : Nil)
if HOSTS.empty?
STDERR.puts "Please specifiy a host by creating a box_nameofyourhost.nix file"
exit 1
end
@hosts = HOSTS
end
def run(cmd : String, args : Array(String), env : Hash(String, String))
puts "#{cmd} #{args.join(" ")}"
output = [] of String
Process.run cmd, args: args, env: env do |cmd|
spawn do
cmd.output.each_line do |line|
output << line
puts line
end
end
spawn do
cmd.error.each_line do |line|
STDERR.puts line
end
end
end
output
end
def run(cmd : String, args : Array(String))
run cmd, args: args, env: ({} of String => String)
end
def run_ssh_each(args : Array(String))
hosts.map do |host|
run("ssh", args: [host] + args)
end
end
def nixos_rebuild(subcmd)
hosts.each do |host|
run "nixos-rebuild",
args: ["--build-host", host, "--target-host", host, subcmd],
env: {"NIXOS_CONFIG" => "#{FileUtils.pwd}/box_#{host}.nix"}
end
end
def switch
nixos_rebuild("switch")
end
def build
nixos_rebuild("build")
end
def status
run_ssh_each(["systemctl", "status"])
end
def failed
run_ssh_each(["systemctl", "list-units", "--state=failed"]).each do |output|
output.each do |line|
# UNIT LOAD ACTIVE SUB DESCRIPTION
# ● gitea.service loaded failed failed gitea
words = line.split
next if words.size != 6
_, unit, load, active, sub, desc = words
next if unit.nil?
end
end
end
end
ops = Ops.new(ARGV[1]?)
case ARGV[0]?
when "switch"
ops.switch
when "build"
ops.build
when "status"
ops.status
when "failed"
ops.failed
else
STDERR.puts "You must specify a command like (switch|status)"
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment