Create a docker secret on the CLI without logging the secret itself
November 22, 2024•350 words
When creating docker secrets on the command line, there is a problem with the example command provided by the Docker documentation.
If you create a secret in this way, your secret will end up in your bash history, and perhaps even worse; if your organization logs all terminal commands, it will be kept in a central log store somewhere, perhaps indefinitely.
Sure, you could append a command like the one below to immediately remove the last command from your shell history.
(printf "This is a secret" | docker secret create my_secret_data -) && history -d $(history 1)
But what about terminal logging? Well, that’s a little more complicated, but not really. I was watching a screen share with my very smart co-worker earlier this evening and saw his method, which is much more secure. It’s also simple.
vi +startinsert dsc
First, we use vi (or whatever) to open a file named dsc. Since we’re already set to insert, all we have to do is paste the secret value in.
Then, just hit the Esc key, and type :wq. Now you have a file named dsc with your secret value inside of it.
Finally, we use cat and a pipe to redirect the output of the command—which is the secret value inside of the dsc file—into a docker secret instead of echoing the output into the terminal.
cat dsc | docker secret create secretTitle -
That’s it! You should see the docker secret id echo to your terminal, which means it’s created.
docker secret ls
This should show you all of your docker secrets, including the one you just created, which means we’re done!
Pretty cool.
Make sure you remember to delete the file. In fact, I would just append it to the create we did previously.
cat dsc | docker secret create secretTitle - && rm dsc
Nice and clean. Create the secret, delete the trail, and then check your history, which should only show the command we ran, but not the secret we set with it.
history