Ansible如何将指定IP列表按要求格式写入配置文件
Ansible生成指定格式IP配置的实现方案
你可以通过以下三种常用方式实现需求,可根据你的场景选择:
方案1:使用Jinja2模板(推荐全量生成配置场景)
- 新建Jinja2模板文件,命名为
dbr_exclude.conf.j2,内容如下:
{% for ip in provider.ip_list %} dbr:excludeRange({"{{ ip }}"}) -- {{ provider.name }} {% endfor %}
- 编写Ansible任务调用template模块生成配置:
- name: 生成dbr排除IP配置文件 ansible.builtin.template: src: /path/to/dbr_exclude.conf.j2 dest: /etc/your_app/dbr.conf mode: '0644'
方案2:无需单独模板,使用copy模块 inline 生成
如果不想单独维护模板文件,可直接把Jinja2逻辑写在copy模块的content参数中:
- name: 直接生成dbr排除IP配置 ansible.builtin.copy: content: | {% for ip in provider.ip_list %} dbr:excludeRange({"{{ ip }}"}) -- {{ provider.name }} {% endfor %} dest: /etc/your_app/dbr.conf mode: '0644'
方案3:逐行追加写入(适用需要保留原有文件内容的场景)
如果目标文件已有其他内容,只需要追加对应IP规则,可使用loop配合lineinfile模块实现:
- name: 逐行追加dbr排除IP规则 ansible.builtin.lineinfile: path: /etc/your_app/dbr.conf line: 'dbr:excludeRange({"{{ item }}"}) -- {{ provider.name }}' regexp: '^dbr:excludeRange\({"{{ item }}"\})' state: present create: yes loop: "{{ provider.ip_list }}"
注意事项
- 方案1、2会直接覆盖目标文件内容,适合需要全量生成配置的场景
- 方案3的regexp参数可避免重复写入相同IP的规则,可根据实际需求决定是否保留
- 所有路径请替换为你实际使用的模板路径和目标配置文件路径
内容的提问来源于stack exchange,提问作者pyramid13
相关产品推荐
相关产品推荐

