Bitbucket Pipeline multiline environment variables

1 minute read

I recently had a case where I wanted to use a ssh private key in a Bitbucket Pipeline, and found out that Bitbucket Pipeline environment variables do not support multi-line values. Atlassian’s suggestion to solve this is to use Bitbucket Deployments, a premium feature, and I didn’t find many other good suggestions.

Obviously there are some security issues with putting a private key into a build using a variable, but there are cases where you may need to anyway, and also lots of other cases you may want a multi-line value for a variable that aren’t as risky.

A simple workaround for this is to convert your multi-line file into a delimited string, then convert it back in the pipeline file. I believe the simplest solution for this is to use the tr command. Likely there are some length limitations in Bitbucket’s environment variables, you may need to check this if you have a longer file.

In my case, I generated the delimited file using something like this:

tr '\n' '|' < keyfile > newkeyfile

Then I pasted the long string into the environment variable, and then in the pipeline converted it back using something like this:

echo $MYVAR | tr '|' '\n' > keyfile

For ssh keys you also need to either set umask before creating the file (more safe) or chmod the file immediately after creating (slight race condition risk).

Hope this is useful for someone else!