Search code examples
elixirgithub-actions

Appending lines to a file whose path is defined in an environment variable


I enjoy using Elixir as a scripting language in GitHub actions.

At the moment, defining output values for a workflow step in Github actions requires that you run the following bash command:

echo "key=value" >> $GITHUB_OUTPUT

I guess what's happening here is that we are appending key=value to some file whose path is stored under the environment variable $GITHUB_OUTPUT.

I'm trying to do this from Elixir, but I'm a bit stuck. I've tried the following:

IO.puts("echo 'key=value' >> $GITHUB_OUTPUT")
IO.puts("key=value >> $GITHUB_OUTPUT")
System.cmd("echo", ["hello=world", ">>", "$GITHUB_OUTPUT")

How can I append lines to a file whose path is stored in an environment variable?


Solution

  • Use System.fetch_env!/1 to get the environment variable, and File.open!/2 with IO.puts/2 to append to the file:

    "GITHUB_OUTPUT"
    |> System.fetch_env!()
    |> File.open!([:write, :append])
    |> tap(&IO.puts(&1, "key=value"))
    |> File.close()