Shell变量在文本文件中扩展,保留空格(例如Rancher中的docker-compose.yml用法)

问题描述 投票:1回答:2

我想在YAML文件中使用默认值执行shell扩展,保留其结构和前导空格,以便保持其可用性。

例如:

version: 2

services:
    postgres: 
       image: ${POSTGRESQL_IMAGE:-my-private-registry/postgres}:${POSTGRESQL_BUILD:-9.6}"
       labels:
           io.rancher.scheduler.affinity:host_label: myproject=true

    myapp:
       image: ${APP_IMAGE:-my-private-registry/myapp}:${APP_BUILD:-latest}
       depends_on:
           - postgres
...

输出应该像:

version: 2

services:
    postgres: 
       image: my-private-registry/postgres:9.6
       labels:
           io.rancher.scheduler.affinity:host_label: myproject=true

    myapp:
       image: my-private-registry/myapp:latest
       depends_on:
           - postgres
...

我想获得renderes docker-compose文件,所以我可以将它传递给Rancher,它只支持version 2而不进行shell扩展。

什么是最好和最可靠的解决方案?

我试过了:

  • qazxsw大便,但它只能执行原始替换
  • shell envsubst但它删除了前导空格和破坏文件
shell docker-compose yaml rancher variable-expansion
2个回答
1
投票

最后,我通过eval保留空间来解决方案:

eval

说明:

  • while IFS= read -r; do eval echo "\"""${REPLY}""\""; done < docker-compose.yml 没有为IFS=命令设置分隔符,因此它尝试不拆分字符串(可选)
  • read保留文件中的反斜杠
  • read -r调用没有变量名称将整个字符串放入没有空格修剪到默认变量read
  • REPLY呈现变量并在其周围保留所需的双引号数,以使字符串可正确打印

更新:

改变echo "\"""${REPLY}""\""也很有用:

version

0
投票

我更容易在shell脚本中执行变量扩展(而不是while),然后用sed替换.yml(使用更简单的关键字进行替换)

© www.soinside.com 2019 - 2024. All rights reserved.