如何用jq的ascii_downcase转换docker-compose环境变量键名
转换Docker Compose环境变量键名:大写转小写+下划线替换为连字符
需求与问题
需要将Docker Compose配置中的环境变量键名全部转换为小写,并把下划线替换为连字符,同时保留变量值的原始大小写。已成功实现服务键名的转换,但对环境变量的转换尝试未生效。
原始配置片段(JSON格式)
{ "name": "qualimarc-docker-prod", "services": { "qualimarc-watchtower": { "cpus": 0.5, "command": null, "container_name": "qualimarc-watchtower", "entrypoint": null, "environment": { "WATCHTOWER_CLEANUP": "true", "WATCHTOWER_DEBUG": "false", "WATCHTOWER_NOTIFICATIONS": "slack", "WATCHTOWER_NOTIFICATION_SLACK_CHANNEL": "#notif-qualimarc", "WATCHTOWER_NOTIFICATION_SLACK_HOOK_URL": "https://hooks.slack.com/services/TCRRETSQ4/B03QN4MTU3B/", "WATCHTOWER_NOTIFICATION_SLACK_IDENTIFIER": "diplotaxis1-prod qualimarc-watchtower", "WATCHTOWER_NO_STARTUP_MESSAGE": "true", "WATCHTOWER_POLL_INTERVAL": "60", "WATCHTOWER_RUN_ONCE": "false", "WATCHTOWER_SCOPE": "qualimarc-watchtower-scope", "WATCHTOWER_WARN_ON_HEAD_FAILURE": "never" }, "image": "containrrr/watchtower:1.4.0", "labels": { "com.centurylinklabs.watchtower.scope": "qualimarc-watchtower-scope" }, "mem_limit": "3221225472", "memswap_limit": "3221225472", "networks": { "default": null }, "restart": "unless-stopped", "volumes": [ { "type": "bind", "source": "/var/run/docker.sock", "target": "/var/run/docker.sock", "bind": { "create_host_path": true } } ] } } }
已实现的服务键名转换命令
echo $(docker-compose config --format json) | jq '.services|with_entries(.key|=ascii_downcase)'
之前尝试的无效命令
echo $(docker-compose config --format json) | jq '.services|with_entries(.value|with_entries(.key|=ascii_upcase))'
解决方案
使用以下jq命令可完成环境变量键名的转换,同时保留值的原始大小写:
echo $(docker-compose config --format json) | jq '.services |= with_entries(.value.environment |= with_entries(.key |= (ascii_downcase | gsub("_"; "-"))))'
命令解释
.services |= with_entries(...):遍历所有服务,对每个服务的配置进行修改.value.environment |= with_entries(...):针对服务下的environment字段,遍历其键值对.key |= (ascii_downcase | gsub("_"; "-")):将键名先转为小写,再把下划线替换为连字符
转换后的environment片段效果
"environment": { "watchtower-cleanup": "true", "watchtower-debug": "false", "watchtower-notifications": "slack", "watchtower-notification-slack-channel": "#notif-qualimarc", "watchtower-notification-slack-hook-url": "https://hooks.slack.com/services/TCRRETSQ4/B03QN4MTU3B/", "watchtower-notification-slack-identifier": "diplotaxis1-prod qualimarc-watchtower", "watchtower-no-startup-message": "true", "watchtower-poll-interval": "60", "watchtower-run-once": "false", "watchtower-scope": "qualimarc-watchtower-scope", "watchtower-warn-on-head-failure": "never" }
同时转换服务键名和环境变量键名
如果需要一次性完成服务键名小写转换+环境变量键名格式转换,可使用合并命令:
echo $(docker-compose config --format json) | jq '.services |= with_entries(.key |= ascii_downcase | .value.environment |= with_entries(.key |= (ascii_downcase | gsub("_"; "-"))))'
内容的提问来源于stack exchange,提问作者Nathanaël Blanchet
相关产品推荐
相关产品推荐

