如何通过Ansible高效动态为Supervisor配置文件添加多应用路径
Great question! Your current setup works but lacks flexibility for scaling or managing different server configurations. The cleanest way to solve this is to use host-specific variables to define the list of applications per server, then dynamically generate the files line in your Supervisor config using Jinja2 templating. Here's how to implement it step by step:
Step 1: Define Application Lists in Host/Group Variables
Instead of hardcoding app_name and app_name2 as global defaults, create a list variable (e.g., supervisor_apps) in host-specific variables (or group variables if multiple servers share the same app set).
For example, in host_vars/ser-db-10.yml:
supervisor_apps: - user: app name: bla - user: dev name: blabla
You can add as many entries as needed here—4 apps would just mean 4 items in the list. For servers that don't need extra app paths, you can either omit this variable entirely or set it to an empty list.
Step 2: Refactor the Ansible Task
Replace your hardcoded line with a Jinja2 expression that dynamically builds the path strings from the supervisor_apps variable. We'll also replace the hardcoded when condition with a check for the existence of this variable.
Update /roles/supervisor/tasks/main.yml:
- name: Add dynamic app paths to Supervisor include section lineinfile: dest: /etc/supervisor/supervisord.conf regex: '^files =' line: >- files = /etc/supervisor/conf.d/*.conf {% for app in supervisor_apps | default([]) %} /home/{{ app.user }}/{{ app.name }}/releases/{{ app.user }}/shared/supervisor/*.conf {% endfor %} when: supervisor_apps is defined and supervisor_apps | length > 0 notify: restart supervisor tags: multi_workers
Key Details:
- The
>-syntax lets us write the line across multiple lines for readability, while Jinja2 processes it into a single whitespace-separated line. default([])ensures the task doesn't fail ifsupervisor_appsisn't defined on a server.- The
whencondition only runs the task on servers where we've defined a non-emptysupervisor_appslist.
Step 3: (Optional) Add Default Fallback
If you want to ensure the base conf.d/*.conf path is always present even when no apps are defined, add a separate task for the baseline config:
- name: Ensure base Supervisor include path exists lineinfile: dest: /etc/supervisor/supervisord.conf regex: '^files =' line: 'files = /etc/supervisor/conf.d/*.conf' when: supervisor_apps is not defined or supervisor_apps | length == 0 notify: restart supervisor tags: multi_workers
This way, every server gets the base config, and servers with apps get the extra paths appended automatically.
Why This Works:
- Flexibility: Add or remove apps per server just by updating the host variable list—no need to edit the task itself.
- Maintainability: No hardcoded hostnames or paths, making the role reusable across your entire infrastructure.
- Scalability: Supports any number of apps without changing the core task logic.
内容的提问来源于stack exchange,提问作者Brzozova

