如何在Ansible中通过循环动态生成docker-compose配置文件
解决方案
步骤1:完善服务配置YML
将每个服务的独有配置(端口、额外主机、环境变量等)补充到你的服务定义YML中,后续直接从该文件读取所有配置,无需在模板硬编码:
services: - service: "front" image: "acalls-caselog-web-app" version: "latest" ports: - "81:81" extra_hosts: - "backend:172.32.3.46" environment: profile: preproduction - service: "back" image: "acalls-caselog-web-service" version: "latest" ports: - "20101:20101" environment: profile: preproduction - service: "vb" image: "acalls-caselog-vb-service" version: "latest" ports: - "20102:20102" environment: profile: preproduction - service: "salesforce" image: "acalls-caselog-salesforce-app-service" version: "latest" ports: - "20103:20103" environment: profile: preproduction - service: "tts" image: "ydilo-tts-service" version: "latest" ports: - "20104:20104" environment: profile: preproduction - service: "ai_classifier" image: "acalls-caselog-ai-classifier-service" version: "latest" ports: - "20105:20105" environment: profile: preproduction
注意:请将原配置中的
ai classifier改为ai_classifier,Docker Compose服务名称不支持空格。
步骤2:修改Ansible任务文件
在原有任务前增加加载服务配置的步骤,假设你的服务配置YML文件路径为vars/service_list.yml:
--- - name: 加载服务配置列表 include_vars: file: vars/service_list.yml - name: 停止现有容器 ignore_errors: yes become: True shell: cmd: "docker-compose down" chdir: /你的部署目录路径 - name: 生成docker-compose配置文件 template: src: docker-compose-acalls.yml.j2 dest: /你的部署目录路径/docker-compose.yml mode: 0700 - name: 启动容器 become: True shell: cmd: "nohup docker-compose -f docker-compose.yml up -d" chdir: /你的部署目录路径
步骤3:编写Jinja2模板文件(docker-compose-acalls.yml.j2)
使用Jinja2循环语法遍历服务列表,动态生成服务配置,完全不需要硬编码数组下标:
version: "3.3" services: {% for svc in services %} {{ svc.service }}: image: 你的镜像仓库地址/{{ svc.image }}:{{ svc.version }} {% if svc.ports is defined %} ports: {% for port in svc.ports %} - "{{ port }}" {% endfor %} {% endif %} {% if svc.extra_hosts is defined %} extra_hosts: {% for host in svc.extra_hosts %} - "{{ host }}" {% endfor %} {% endif %} {% if svc.environment is defined %} environment: {% for key, value in svc.environment.items() %} {{ key }}: {{ value }} {% endfor %} {% endif %} {% endfor %}
模板里加了字段存在性判断,部分服务没有的配置(比如extra_hosts)不会生成对应字段,避免语法错误。
内容的提问来源于stack exchange,提问作者Alejandro Sánchez
相关产品推荐
相关产品推荐

