nixos modules for convenient deployment of cloud resources
1use std/log 2 3def main [firewallId: number, rulesFile: path, --auth-token (-t): string] { 4 let auth_token: string = if $auth_token == null { $env.HETZNER_API_TOKEN? } else { $auth_token } 5 let authHeader: list<string> = ["authorization" $"Bearer ($auth_token)"] 6 7 def makeApiUrl [path: string] { 8 return $"https://api.hetzner.cloud/v1($path)" 9 } 10 def post [path: string] { 11 $in | http post -e --full -H $authHeader --content-type application/json (makeApiUrl $path) 12 } 13 def get [path: string] { 14 http get -e --full -H $authHeader (makeApiUrl $path) 15 } 16 17 # first fetch firewall to see if it even exists 18 let resp = get $"/firewalls/($firewallId)" 19 if $resp.status == 404 { 20 log error $"provided firewall \(id ($firewallId)\) does not exist" 21 exit 1 22 } else if $resp.status != 200 { 23 log error $"could not get firewall \(id ($firewallId)\):\n($resp.body.error | to text -n)" 24 exit 1 25 } 26 let firewall = $resp.body | get firewall 27 28 # backup firewall 29 let backupPath = $".hetzner/($firewallId).json" 30 mkdir .hetzner; $firewall | to json | save -f $backupPath 31 log info $"backing up firewall ($firewallId) to ($backupPath)" 32 33 # apply rules 34 let resp = open $rulesFile | post $"/firewalls/($firewallId)/actions/set_rules" 35 if $resp.status != 201 { 36 log error $"could not apply firewall \(id ($firewallId)\):\n($resp.body.error | to text -n)" 37 exit 2 38 } 39 log info $"applied firewall ($firewallId)" 40}