lawik

lawik

Nerves Core Team

Using a NervesHub support script to connect to tailscale

This is a ridiculous hack that I did yesterday to verify something we might want to tool up properly for NervesHub.

If you have Tailscale and a Nerves device with NervesHubLink connected to a NervesHub (such as NervesCloud.com) you can add the script below as a Support Script and if you run the script, the device should join your Tailnet and become routable.

It will also start EPMD and make the device an Erlang node. Then you could ridiculous and use a variant of my nerves_node hack to make the nodes connect up into a cluster. That’s not what we want to do. Rather we open a Livebook, then add a Smart cell for Remote Execution. Grab the cookie and host that the script prints. Bob is now your uncle.

You get all of Kino and access to pull things from your device. You can also connect the Livebook to the device but Mix.install won’t work for you and you’ll be quite limited in what you can do. But it has uses.

I don’t recommend this for production quite yet. I realized while writing this that I should restrict epmd to listen only to the Tailscale IP to be diligent for example. But it is probably already a pretty good debug tool if you need more direct access to your node. It means you can SSH via terminal (unless you’ve switched that off) and that also means you can deliver firmware via mix upload.

Enough of that. The hack script itself:

:inets.start()
:ssl.start()

url = ~c"https://pkgs.tailscale.com/stable/tailscale_1.82.0_arm64.tgz"
# You can use an ephemeral key to make ephemeral devices
# tags should be good for categorizing devices
# re-usable is required for it to work multiple times
tailscale_key = "MY_TAILSCALE_AUTH_KEY"
headers = []

tailscale_dir = "/data/tailscale"
File.mkdir_p!(tailscale_dir)
tmp_path = Path.join(tailscale_dir, "tailscale.tgz")

filepaths = Path.wildcard(Path.join(tailscale_dir, "/**"))

daemon_path =
  Enum.find(filepaths, fn path ->
    Path.basename(path) == "tailscaled"
  end)

cli_path =
  Enum.find(filepaths, fn path ->
    Path.basename(path) == "tailscale"
  end)

if is_nil(daemon_path) and is_nil(cli_path) do
  http_request_opts = [
    ssl: [
      cacerts: :public_key.cacerts_get(),
      customize_hostname_check: [
        match_fun: :public_key.pkix_verify_hostname_match_fun(:https)
      ]
    ]
  ]

  IO.puts("to path: #{tmp_path}")

  {:ok, :saved_to_file} =
    :httpc.request(:get, {url, headers}, http_request_opts, stream: String.to_charlist(tmp_path))

  # {:ok, file} = :file.open(tmp_path, [:read, :compressed, :raw])

  {:ok, files} =
    :erl_tar.extract({:binary, File.read!(tmp_path)}, [:memory, :verbose, :compressed])

  Enum.each(files, fn {filename, content} ->
    IO.puts(filename)
    File.mkdir_p!(Path.dirname(Path.join(tailscale_dir, filename)))
    File.write!(Path.join(tailscale_dir, filename), content)
  end)
end

filepaths = Path.wildcard(Path.join(tailscale_dir, "/**"))

daemon_path =
  Enum.find(filepaths, fn path ->
    Path.basename(path) == "tailscaled"
  end)

cli_path =
  Enum.find(filepaths, fn path ->
    Path.basename(path) == "tailscale"
  end)

File.chmod(daemon_path, 0o700)
File.chmod(cli_path, 0o700)

case Process.whereis(Tailscale) do
  nil ->
    {:ok, _pid} =
      MuonTrap.Daemon.start_link(
        daemon_path,
        [
          "--tun=userspace-networking",
          "--statedir=#{tailscale_dir}"
        ],
        name: Tailscale
      )

  _ ->
    :ok
end

{output, 0} =
  System.cmd(cli_path, ["up", "--auth-key=#{tailscale_key}", "--accept-routes"],
    stderr_to_stdout: true
  )

{ip, 0} =
  System.cmd(cli_path, ["ip", "-4"])

ip = String.trim(ip)

cookie = Base.encode64(:crypto.strong_rand_bytes(64))

case Process.whereis(EPMD) do
  nil ->
    {:ok, pid} = MuonTrap.Daemon.start_link("epmd", [], name: EPMD)

  _ ->
    :ok
end

Node.stop()
{:ok, _pid} = Node.start(:"nerves@#{ip}")

Node.set_cookie(String.to_atom(cookie))
IO.puts("Host: nerves@#{ip}")
IO.puts("Cookie: #{cookie}")

I tried making it fairly idempotent. It shouldn’t redo very much work and it should work if it has half-succeeded in the past. A reboot will shut it all down and I name the processes so you can make a script to shut it back down.

A fun nuance is that most of the practical management ends up on the tailscale key configuration. There are things we could do while calling the Tailscale CLI, but since your key can be set to tag devices and decide if they are ephemeral or permanent the script can be quite dumb.

Most Liked

lawik

lawik

Nerves Core Team

I’ve bothered @hugobarauna a little bit about being able to use this via livebook.dev/run and pass some parameters along aside from the URL. Ideally I’d want to smuggle the node string and cookie over there so I could pick it up from the Livebook itself.

Give a smooth integration between NervesHub and Livebook Desktop/Teams.

If any of you try this on your Nerves devices, let me know how it goes.

lawik

lawik

Nerves Core Team

Oh, btw, if you don’t use NervesHub you could still do this in console, should be fine.

If you want to run this without Nerves you’ll need to pick different directories and you might replace the calls to MuonTrap with System.cmd or something. Perfectly doable stuff in just Elixir as well.

nix2intel

nix2intel

this is awesome!

Where Next?

Popular in Discussions Top

jswny
I would like to better understand what the advantages/disadvantages of umbrella applications are compared to structuring your app as as s...
New
Fl4m3Ph03n1x
Background This question comes mainly from my ignorance. Today is Black Friday, one of my favorite days of the year to buy books. One boo...
New
praveenperera
How We Replaced React with Phoenix By: Thought Bot
New
AstonJ
I’ve just started the Phoenix part of the utterly brilliant online course by @pragdave. On generating the Phoenix app he uses the --no-ec...
New
IVR
Hi all, I’ve seen a number of related threads in the past, but I’d still be very curious to hear an up-to-date opinion on this topic. I...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New
restack_oslo
Hello, Please pardon me for any faux paux. I am 46 and this is my first time on a forum of any kind. I wanted to to get answers from tho...
New
RudManusachi
What configs will make sense to put to runtime.exs? – A bit of how I configure apps: I have generic configs in config/config.exs, dev...
New
chulkilee
Here are the list of HTTP client libraries/wrappers, and some thoughts on HTTP client in general. I’d like to hear from others how they w...
New
AstonJ
Can you believe the first professionally published Elixir book was published just 8 years ago? Since then I think we’ve seen more books f...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement