如何用yq批量修改docker-compose中前缀匹配服务的镜像?
使用yq批量修改Docker Compose中指定前缀服务的镜像
针对你的需求,直接使用以下yq命令即可批量更新所有以app_sandbox为前缀的服务镜像:
# 预览修改结果(不改动原文件) yq '.services |= with_entries(select(.key | test("^app_sandbox")) | .value.image = "some-image:latest")' docker-compose.yml # 直接修改原文件(原地编辑) yq -i '.services |= with_entries(select(.key | test("^app_sandbox")) | .value.image = "some-image:latest")' docker-compose.yml
原命令不生效的原因
你之前用了select(.key == "app_sandbox*"),但==是精确匹配,不会解析通配符*,所以无法匹配到任何服务。需要用test()函数结合正则表达式实现前缀匹配:test("^app_sandbox")中的^表示以指定字符串开头,能准确筛选出目标服务。
命令分解
.services |= ...:对services节点执行修改操作,并将结果赋值回原节点with_entries(...):遍历services下的所有键值对(即各个服务)select(.key | test("^app_sandbox")):筛选出服务名称以app_sandbox开头的条目.value.image = "some-image:latest":将选中服务的image字段更新为目标镜像版本
输入输出示例
输入的Docker Compose文件:
--- version: '3.4' services: app_sandbox_zeta: image: some-image:not-latest app_sandbox_sigma: image: some-image:not-latest general_app: ... some_app: ...
执行命令后输出:
--- version: '3.4' services: app_sandbox_zeta: image: some-image:latest app_sandbox_sigma: image: some-image:latest general_app: ... some_app: ...
内容的提问来源于stack exchange,提问作者Demmy
相关产品推荐
相关产品推荐

