I would like to do something like this in my amazon_s3.yml config file:
access_key_id: ENV['S3_KEY']
secret_access_key: ENV['S3_SECRET']
...but I know this isn't working. Not sure if it is even possible, but can you put Ruby code in a YAML file?
Not normally / directly. I say this because in order to use ruby results you need to use something like ERB first before loading the file. In terms of code, you need to go from something like:
loaded_data = YAML.load_file("my-file.yml")
Or even
loaded_data = YAML.load(File.read("my-file.yml"))
To:
loaded_data = YAML.load(ERB.new(File.read("my-file.yml")).result)
In this specific case, you would have to look at what is loading the file - in some cases,
it may already be designed to load it straight out of the environment or you may need to either:
- Monkey Patch the code
- Fork + Use your custom version.
Since there are a few plugins that use amazon_s3.yml, It might be worth posting which library you are using that uses it - alternatively, I believe from a quick google that the AWS library lets you define AMAZON_ACCESS_KEY_ID and AMAZON_SECRET_ACCESS_KEY as env vars and it will pick them up out of the box.
You can if it is interpreted through ERB, in which case it acts like an ERB view and Ruby code goes between <%
and %>
Try:
access_key_id: <%= ENV['S3_KEY'] %>
secret_access_key: <%= ENV['S3_SECRET'] %>
... and see if it works
Using fd.'s example, try swapping out the ERB syntax with string interpolation if your application is configure to use HAML. E.g.,:
access_key_id: #{ENV['S3_KEY']}
secret_access_key: #{ENV['S3_SECRET']}
instead of:
access_key_id: <%= ENV['S3_KEY']} %>
secret_access_key: <%= ENV['S3_SECRET'] %>
Works like a charm for me without any additional code (Rails 4.2):
default: &default
adapter: <%= 'mysql2' %>
In rails 4.2 using ERB syntax will evaluate the code and return strings.
# environment variables
S3_KEY=01234
S3_SECRET=56789
# yaml file
access_key_id: <%= ENV['S3_KEY'] %>
secret_access_key: <%= ENV['S3_SECRET'] %>
# then you can do
ENV.fetch('access_key_id')
=> "01234"
ENV.fetch('secret_access_key')
=> "56789"
You can also write ruby code in a string in your YAML file and then evaluate it later
# yaml file
retry_interval: '5.minues'
# then you can do
eval(ENV.fetch('retry_interval'))
=> 300 seconds
CAUTION: be very careful when using eval as it can post a serious security risk