Search code examples
bashenvironment-variablesglobal-variablesaudio-streamingplaylist

Store an API_KEY in an env var and use in a playlist URL


I use a streaming service (di.fm) that has many channels. Each channel has a playlist I stream from the CLI (using mpv). Each URL in each playlist stores the API KEY.

I want to store the API KEY outside of the individual playlists, so for example, if I change the API KEY, I don't have to change every playlist.

I'm on a Mac.

1) What is the best (safest) place to declare export DI_KEY=""? In .bashrc was my first thought, except I back it up to github. Any other better place to declare the env var that will be created each time I enter bash?

2) In the playlist file, how do I use the $DI_KEY in the URL?

[playlist]
NumberOfEntries=1
File1=http://prem4.di.fm:80/00sclubhits?$DI_KEY
Title1=DI.FM - 00s Club Hits
Length1=0
Version=2

Just referencing it directly doesn't work.

enter image description here

I'm sure this may be answered elsewhere, but in all my searching I couldn't find any helpful answers, particularly to questions 2.


Solution

  • Regarding setting env variables outside of .bashrc, you could create a separate file to define sensitive variables and source this from within your .bashrc.

    For example, create a file ~.my-private-variables, add the filename to your .gitignore and add the line export DI_KEY="12345" to this file. Then add the following block in .bashrc:

    if [ -f ~/.my-private-variables ]; then                                                                               
      . ~/.my-private-variables                                                                                         
    fi  
    

    Regarding the playlist file, bash is not running the file, so the environment variable is not expanded.

    You could dynamically generate the playlist when bash starts, something like this:

    #!/bin/bash
    
    filename=playlist-1.pls
    baseurl=http://prem4.di.fm:80
    
    cat << EOF > $filename
    [playlist]
    NumberOfEntries=1
    File1=${baseurl}/00sclubhits?${DI_KEY}
    Title1=DI.FM - 00s Club Hits
    Length1=0
    Version=2
    EOF
    

    This will expand the variable and write it to the file, in this case playlist-1.pls in the current working directory. You might add an absolute path to the filename variable that references your playlists directory.

    To run this, you could create a script called playlist-generator and source this in .bashrc as described above. You could add as many playlists as you like here.