如标题中所述,当我尝试从csv文件读取并且仅想读取“名称”列时,“列表对象”没有属性“名称”错误。
我的csv:
name,uid,gid,password
eg1,1,2,password
eg2,1,2,password
我遵循了Ansible官方文档。
我的可笑剧本:
---
- hosts: localhost
become: yes
become_method: sudo
become_user: root
tasks:
- name: read from CSV
read_csv:
path: user-creation.csv
register: users
- debug:
msg: "{{users.list.name}}"
我得到的错误:
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'name'\n\nThe error appears to be in '/root/ansible/main.yml': line 12, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - debug:\n ^ here\n"}
我到处都有Google搜索,似乎大多数人都不使用此模块,或者他们在使用该模块时没有这个问题。
答案 0 :(得分:2)
可以使用json_query。下面的任务
- debug:
msg: "{{ users.list|json_query('[*].name') }}"
给予
"msg": [
"eg1",
"eg2"
]
答案 1 :(得分:1)
知道了
- name: read from CSV
read_csv:
path: user-creation.csv
register: users
- debug:
msg: "{{ item.name }}"
with_items:
- "{{ users.list }}"
输出:
ok: [localhost] => (item={'name': 'eg1', 'uid': '1', 'gid': '2', 'password': 'password'}) => {
"msg": "eg1"
}
ok: [localhost] => (item={'name': 'eg2', 'uid': '1', 'gid': '2', 'password': 'password'}) => {
"msg": "eg2"
附带说明;如果您确实沉迷于此类任务,则可以使用例如awk
实现您的目标。