简体   繁体   English

Rails secrets.yml,其值包含换行符

[英]Rails secrets.yml with values containing newlines

Let's assume I have a config/secrets.yml file that contains:假设我有一个config/secrets.yml文件,其中包含:

development:
  app_name: MyApp
  secret: <%= ENV['SECRET_VALUE'] %>

If I set SECRET_VALUE with a newline, it will break.如果我用换行符设置SECRET_VALUE ,它将中断。 Eg:例如:

export SECRET_VALUE=$(printf "hello\nworld")

Then when I start my rail application I get this error:然后当我启动我的铁路应用程序时,我收到了这个错误:

/usr/local/lib/ruby/3.0.0/psych.rb:457:in 'parse': (<unknown>): could not find expected ':' while scanning a simple key at line 4 column 1 (Psych::SyntaxError)

While debugging the issue, I realized that the literal value of ENV['SECRET_VALUE'] is added to the yaml file before parsing it .在调试问题时,我意识到ENV['SECRET_VALUE']的文字值在解析之前已添加到 yaml 文件中。 That means if I wanted to achieve what I'm trying to do, I would have to do something like:这意味着如果我想实现我想要做的事情,我将不得不做类似的事情:

export SECRET_VALUE=$(printf "|\n hello\n world")

This works but this is very ugly and I can't be the only one who think this behaviour is absurd??这行得通,但这很丑陋,我不能是唯一一个认为这种行为荒谬的人? Is there a better way to do this?有一个更好的方法吗?

EDIT:编辑:

I tried adding quotes around the value:我尝试在值周围添加引号:

development:
  app_name: MyApp
  secret: "<%= ENV['SECRET_VALUE'] %>"

It "works" but the newline gets removed from the string...它“有效”,但换行符从字符串中删除......

root@4e4431bae32e:/app# rails console
Loading development environment (Rails 7.0.3)
irb(main):001:0> puts ENV['SECRET_VALUE']
hello
world
=> nil
irb(main):002:0> puts Rails.application.secrets[:secret]
hello world
=> nil

It's important that the newline remains for my use case.对于我的用例来说,换行符保留很重要。

You can use an escaped quoted string.您可以使用转义的引号字符串。 YAML's string format is similar enough to a superset of Ruby's for String#dump to work: YAML 的字符串格式与 Ruby 的超集非常相似,以便String#dump工作:

development:
  app_name: MyApp
  secret: <%= ENV['SECRET_VALUE'].dump %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM