community.general.read_csv 模块 – 读取 CSV 文件

注意

此模块是 community.general 集合(版本 10.1.0)的一部分。

如果您正在使用 ansible 包,您可能已经安装了此集合。它不包含在 ansible-core 中。要检查它是否已安装,请运行 ansible-galaxy collection list

要安装它,请使用:ansible-galaxy collection install community.general

要在 playbook 中使用它,请指定:community.general.read_csv

概要

  • 读取 CSV 文件并返回一个列表或字典,其中每个行包含一个字典。

参数

参数

注释

delimiter

字符串

用于分隔字段的单字符字符串。

使用此参数时,您将更改 dialect 使用的默认值。

默认值取决于使用的方言。

dialect

字符串

解析 CSV 文件时要使用的 CSV 方言。

可能的值包括 excelexcel-tabunix

默认值: "excel"

fieldnames

列表 / elements=字符串

每列的字段名称列表。

如果 CSV 没有标题,则需要此项。

key

字符串

用作结果字典的键的列名。

如果未设置 key,则模块将返回一个字典列表,其中每个字典是 CSV 文件中的一行。

path

别名:filename

路径 / 必需

从中读取数据的 CSV 文件名。

skipinitialspace

布尔值

是否忽略紧跟在分隔符后的任何空格。

使用此参数时,您将更改 dialect 使用的默认值。

默认值取决于使用的方言。

选项

  • false

  • true

strict

布尔值

是否在 CSV 输入错误时引发异常。

使用此参数时,您将更改 dialect 使用的默认值。

默认值取决于使用的方言。

选项

  • false

  • true

unique

布尔值

所用的 key 是否应是唯一的。

选项

  • false

  • true ←(默认)

属性

属性

支持

描述

check_mode

支持: 完全

可以在 check_mode 中运行,并返回已更改的状态预测,而无需修改目标。

diff_mode

支持:

当处于差异模式时,将返回有关已更改(或可能需要在 check_mode 中更改)的详细信息。

另请参阅

另请参阅

ansible.builtin.csvfile lookup 插件

可用于从 Jinja 在 CSV 文件中进行选择性查找。

示例

# Example CSV file with header
#
#   name,uid,gid
#   dag,500,500
#   jeroen,501,500

# Read a CSV file and access user 'dag'
- name: Read users from CSV file and return a dictionary
  community.general.read_csv:
    path: users.csv
    key: name
  register: users
  delegate_to: localhost

- ansible.builtin.debug:
    msg: 'User {{ users.dict.dag.name }} has UID {{ users.dict.dag.uid }} and GID {{ users.dict.dag.gid }}'

# Read a CSV file and access the first item
- name: Read users from CSV file and return a list
  community.general.read_csv:
    path: users.csv
  register: users
  delegate_to: localhost

- ansible.builtin.debug:
    msg: 'User {{ users.list.1.name }} has UID {{ users.list.1.uid }} and GID {{ users.list.1.gid }}'

# Example CSV file without header and semi-colon delimiter
#
#   dag;500;500
#   jeroen;501;500

# Read a CSV file without headers
- name: Read users from CSV file and return a list
  community.general.read_csv:
    path: users.csv
    fieldnames: name,uid,gid
    delimiter: ';'
  register: users
  delegate_to: localhost

返回值

常见的返回值记录在此处,以下是此模块特有的字段

Key

描述

dict

dictionary

CSV 内容作为字典。

已返回: 成功

示例: {"dag": {"gid": 500, "name": "dag", "uid": 500}, "jeroen": {"gid": 500, "name": "jeroen", "uid": 501}}

列表

列表 / elements=字符串

CSV 内容作为列表。

已返回: 成功

示例: [{"gid": 500, "name": "dag", "uid": 500}, {"gid": 500, "name": "jeroen", "uid": 501}]

作者

  • Dag Wieers (@dagwieers)