Passing an environment variable to a shell script from Fastlane

Lorenzo B picture Lorenzo B · Jan 18, 2016 · Viewed 7.6k times · Source

I'm running Fastlane (a continuous build tool for iOS) in order to execute a custom shell script for decrypting a file.

This is the command.

sh "./decrypt.sh ENV['ENCRYPTION_P12']"

I cannot figured out a way to pass the environment variable to that script. Obviously, if I hardcode the pwd into the script, it works correctly.

sh "./decrypt.sh mypwd"

Any suggestions?

Answer

Charles Duffy picture Charles Duffy · Jan 18, 2016

Expanding From Within The Immediate Shell

Assuming that sh, here, is a fastlane command that invokes a shell command with the given argument as script text:

# as a fastlane directive
sh './decrypt.sh "$ENCRYPTION_P12"'

Note that if this were being literally invoked as a command line for /bin/sh, it would need a -c argument:

# in other contexts
sh -c './decrypt.sh "$ENCRYPTION_P12"'

Note that this absolutely depends on ENCRYPTION_P12 being an environment variable -- that is, exported to the environment by the system by which it was set.


Expanding from Within The Invoked Script

That said, if it is an environment variable, you have a better option: Just use it.

That is, inside decrypt.sh, you can refer to "$ENCRYPTION_P12" without needing to set it explicitly, as the shell implicitly imports all environment variables as shell variables -- and they're passed down to child processes without any explicit actions needed.


Things to Avoid: Shell Injection Attacks

Finally, an aside: The dangerous way to do this would have been something like:

# INSECURE: DO NOT DO THIS
sh "./decrypt.sh #{ENV['ENCRYPTION_P12']}"

or

# STILL INSECURE
sh "./decrypt.sh \"#{ENV['ENCRYPTION_P12'}\""

or

# STILL INSECURE
sh "./decrypt.sh '#{ENV['ENCRYPTION_P12'}'"

...thereby substituting the value into your generated string at the Ruby level. This is dangerous, however, as that string is parsed as code -- meaning that contents of ENCRYPTION_P12 could then be leveraged in shell attacks.

For instance, consider the case (given below in bash syntax):

# this will make any of the above do Very Evil Things
ENCRYPTION_P12=$'$(rm -rf ~)\'$(rm -rf ~)\''

...for which both rms will execute if directly substituted into generated shell script (as opposed to expanded during parameter expansion -- '${foo}' -- which takes place after the expansion phases which make this dangerous have already passed).