是否可以通过shell脚本修改yml文件?

use*_*695 17 ubuntu shell-script text-processing docker yaml

这就是我的 docker-compose.yml 的样子。

nginx:
  container_name: 'nginx'
  image: 'nginx:1.11'
  restart: 'always'
  ports:
    - '80:80'
    - '443:443'
  volumes:
    - '/opt/nginx/conf.d:/etc/nginx/conf.d:ro'
  links:
    - 'anything'
Run Code Online (Sandbox Code Playgroud)

现在我需要通过 shell 脚本(在 ubuntu 服务器上)添加一些内容。我不太确定是否有可能:

  1. 添加新元素到nginx/links,如果它不存在
  2. newthing如果不存在 newthing-block 则追加块

新内容应如下所示:

nginx:
  container_name: 'nginx'
  image: 'nginx:1.11'
  restart: 'always'
  ports:
    - '80:80'
    - '443:443'
  volumes:
    - '/opt/nginx/conf.d:/etc/nginx/conf.d:ro'
    - '/etc/letsencrypt:/etc/letsencrypt'
  links:
    - 'anything'
    - 'newthing'

newthing:
  container_name: foo
  image: 'newthing:1.2.3'
  restart: always
  hostname: 'example.com'
Run Code Online (Sandbox Code Playgroud)

wea*_*ver 14

我写了https://github.com/kislyuk/yq,一个围绕https://stedolan.github.io/jq/的包装器,来解决这个用例。

  • 是:`yq -y '.newthing=...' input.yml > output.yml`。(如果您要进行适当的更新,例如 `sed -i`,yq 还不能自己完成,但您可以使用 `sponge`:`yq -y .newthing=... file.yml |海绵文件.yml`。) (3认同)

小智 8

我写了 yaml_cli ( https://github.com/Gallore/yaml_cli ) 来做你需要的。它基于python。这将是您示例的语法:

yaml_cli \
  -f docker-compose.yml \                # read from and save to file
  --list-append \                        # flag to append to lists instead of replacing existing values
  -s nginx:links newthing \              # add a value of type string; here you need --list-append
  -s newthing:container_name foo \       # key 'newthing' is created automatically
  -s newthing:image 'newthing:1.2.3' \   #
  -s newthing:restart always \           #
  -s newthing:hostname 'example.com'     #
Run Code Online (Sandbox Code Playgroud)

感谢有关 yaml_cli 的反馈。


dir*_*rkt 6

有许多用于 Perl、Python 等的 yaml 库。如果不直接从 shell 脚本执行它,而是使用另一种语言就可以了。

另一种选择是安装命令行yaml processor,并从您的 shell 脚本中调用它。