Class: Kraaken::Cloudflare

Inherits:
Object
  • Object
show all
Defined in:
lib/kraaken/cloudflare.rb

Defined Under Namespace

Classes: Tunnel

Instance Method Summary collapse

Constructor Details

#initialize(config:) ⇒ Cloudflare



12
13
14
# File 'lib/kraaken/cloudflare.rb', line 12

def initialize(config:)
  @config = config
end

Instance Method Details

#create_tunnel(name) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/kraaken/cloudflare.rb', line 22

def create_tunnel(name)
  tunnel_secret = Base64.strict_encode64 SecureRandom.hex(32)
  body = {name:, tunnel_secret:, config_src: "cloudflare"}
  config = {
    config: {
      ingress: [
        {
          hostname: "#{name}.server.nerdgeschoss.de",
          service: "http://traefik:8080"
        },
        {
          hostname: "*.#{name}.nerdgeschoss.de",
          service: "http://traefik"
        },
        {
          service: "http_status:404"
        }
      ]
    }
  }
  res = client.post("/client/v4/accounts/#{credential.username}/cfd_tunnel", body).body["result"]
  tunnel = Tunnel.new(res["id"], res["name"], res["status"], self, res["token"])
  logger.info "Creating tunnel #{name} with id #{tunnel.id}"
  client.put("/client/v4/accounts/#{credential.username}/cfd_tunnel/#{tunnel.id}/configurations", config)
  server_dns = {
    type: "CNAME",
    proxied: true,
    name: "#{name}.server.nerdgeschoss.de",
    content: "#{tunnel.id}.cfargotunnel.com"
  }
  logger.info "Creating DNS record for #{name}.server.nerdgeschoss.de"
  client.post("/client/v4/zones/#{zone_id}/dns_records", server_dns)
  app_dns = {
    type: "CNAME",
    proxied: true,
    name: "*.#{name}.nerdgeschoss.de",
    content: "#{tunnel.id}.cfargotunnel.com"
  }
  logger.info "Creating DNS record for #{name}.server.nerdgeschoss.de"
  client.post("/client/v4/zones/#{zone_id}/dns_records", app_dns)
  logger.info "Tunnel #{name} created"
  tunnel
end

#tunnel_token(id:) ⇒ Object



66
67
68
# File 'lib/kraaken/cloudflare.rb', line 66

def tunnel_token(id:)
  client.get("/client/v4/accounts/#{credential.username}/cfd_tunnel/#{id}/token").body["result"] || raise("Could not fetch tunnel token")
end

#tunnel_token_for_name(name) ⇒ Object



70
71
72
# File 'lib/kraaken/cloudflare.rb', line 70

def tunnel_token_for_name(name)
  (tunnels.find { _1.name == name } || create_tunnel(name)).token
end

#tunnelsObject



16
17
18
19
20
# File 'lib/kraaken/cloudflare.rb', line 16

def tunnels
  client.get("/client/v4/accounts/#{credential.username}/cfd_tunnel").body["result"]&.map do |tunnel|
    Tunnel.new(tunnel["id"], tunnel["name"], tunnel["status"], self)
  end || raise("Could not fetch tunnels")
end