一千萬個為什麽

搜索

為什麽不允許在docker-compose.yml中使用布爾值?



在docker-compose.yml文件中定義布爾值:

environment:
  SOME_VAR: true

並運行 docker up ,結果如下:

contains true, which is an invalid type, it should be a string, number, or a null

嘗試解決問題

  1. If true is changed to True the issue persists.
  2. Using 'true' is not accepted by the code itself (a play framework app is started using the ./target/universal/stage/bin/APPNAME -Dplay.evolutions.db.default.autoApply=, i.e. either -Dplay.evolutions.db.default.autoApply=true or -Dplay.evolutions.db.default.autoApply=false parameter):

    VAR has type STRING rather than BOOLEAN

  3. Using yes or no as a variable results in:

    contains true, which is an invalid type, it should be a string, number, or a null

  4. Using yes and using a script that transforms yes to true works

討論</強>

According the docs Any boolean values; true, false, yes no, need to be enclosed in quotes to ensure they are not converted to True or False by the YML parser:

<�強>環境</強>

     

添加環境變量。您可以使用數組或   字典。任何布爾值;真,假,是,不需要   用引號括起來以確保它們不被轉換為True或False   通過YML解析器。

     

只有一個密鑰的環境變量會被解析為它們的值   機器Compose正在運行,這對秘密或有用可能有幫助   特定於主機的值。

<�預> <�代碼>環境:   RACK_ENV:發展   SHOW:'true'   SESSION_SECRET: 環境:    - RACK_ENV =發展    - SHOW = true    - SESSION_SECRET </代碼>

問題</強>

為什麽不允許?

轉載註明原文: 為什麽不允許在docker-compose.yml中使用布爾值?

一共有 2 個回答:

This come from a design choice of YAML language about booleans

每個未加引號的值與這個“正則表達式”匹配:

 y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF

將轉換為 TrueFalse

如果您的代碼將環境值測試為yes或no,例如采用此腳本,則此問題會引發問題(其他示例中的rel =”noreferrer“>):

if [ "$SOME_VAR" == "yes" ];
then
  echo "Variable SOME_VAR is activated"
else
  echo "Variable SOME_VAR is NOT activated"
fi

並設置你的撰寫文件

environment:
  SOME_VAR: yes

當腳本運行時,會導致 SOME_VARTrue ,因此,由於它不等於 yes ,因此采用了錯誤的大小寫。

所以選擇 禁止布爾值,以防止在您不知道YAML規則時難以調試不需要的行為。

我看到了解決問題的兩種方法:

  1. Using an env_file instead, they are not parsed IIRC and should prevent the conversion.

  2. As you already said, use a wrapper script around your launcher to define the value instead before launching the app, something along the line of this should do:

    AUTOAPPLY=false
    if [ "$SOME_VAR" == "true" ]
    then
        AUTOAPPLY=true
    fi
    
    ./target/universal/stage/bin/APPNAME -Dplay.evolutions.db.default.autoApply=$AUTOAPPLY
    

這是YAML。它將 true 解釋為布爾值。 Envars必須是字符串,因此需要通過引號使類型顯式化。

Test this out with https://www.json2yaml.com/