Ansible读取CSV生成模板并分发至服务器报错排查
问题分析与解决方案
错误根源
- CSV未解析为结构化数据:用
lookup('file')读取CSV得到的是纯文本行列表,不是可直接调用属性的字典对象,模板中{{ item.Application }}无法从字符串中获取属性,触发未定义变量错误。 - 循环变量引用错误:
with_items: test_csv未用双大括号包裹变量,实际循环的是字符串test_csv而非变量存储的CSV内容。 - 未关联CSV主机与目标服务器:原逻辑会在每个服务器上循环所有CSV行,无法实现“对应服务器生成对应配置”的需求。
修正后的实现方案
1. 安装依赖集合(若未安装)
ansible-galaxy collection install community.general
2. 修正main.yml代码
- name: 读取并解析CSV文件 community.general.read_csv: path: /u00/ansible/Playbooks/files/newrelic_test.csv key: Host register: test_csv_data - name: 生成对应服务器的配置文件 template: src: /u00/ansible/Playbooks/files/infra-config.yml_template dest: /u00/app/monitor/infra-config.yml when: inventory_hostname == item.key loop: "{{ test_csv_data.dict | dict2items }}" notify: confirm copy done become: yes - name: 启动New Relic服务 ansible.builtin.systemd: name: infra.service state: started become: yes become_user: root
3. 调整模板变量引用
infra-config.yml_template修改为以下内容(适配解析后的字典结构):
custom_attributes: application : {{ item.value.Application }} env : {{ item.value.env }} datacenter : {{ item.value.Datacenter }} log: file: /u00/app/monitor/infra.log
关键逻辑说明
read_csv模块将CSV解析为以Host为键的字典,每个键对应一行的属性集合(如Application、env等)。loop: "{{ test_csv_data.dict | dict2items }}"将字典转为键值对列表,通过when: inventory_hostname == item.key确保仅当前服务器匹配的CSV行才会生成对应配置。- 模板中用
item.value.Application调用属性,因为item是键值对结构,key为主机名,value为该行的所有CSV属性。
预期验证结果
执行Playbook后:
testserver1生成的infra-config.yml包含application : Microsoft、env : TEST、datacenter : DC1testserver2生成的infra-config.yml包含application : Apple、env : TEST、datacenter : DC2
内容的提问来源于stack exchange,提问作者Lucky Ameta
相关产品推荐
相关产品推荐

