如何从Ansible的setup模块输出中获取列表的第一个元素?

60

我从设置模块接收到以下数据:

"ansible_nodename": "3d734bc2a391",
"ansible_os_family": "RedHat",
"ansible_pkg_mgr": "yum",
"ansible_processor": [
  "AuthenticAMD",
  "AMD PRO A10-8700B R6, 10 Compute Cores 4C+6G"
],
"ansible_processor_cores": 1,
"ansible_processor_count": 1,
"ansible_processor_threads_per_core": 1,

我想要获取ansible_processor的第一个值,并在Jinja2模板中使用它。

如果我使用{{ ansible_processor }},它会给我两个值:

"AuthenticAMD",
"AMD PRO A10-8700B R6, 10 Compute Cores 4C+6G"

但我只想要第一个。

3个回答

120

获取列表的第一项:

- debug:
    msg: "First item: {{ ansible_processor[0] }}"

或者:

- debug:
    msg: "First item: {{ ansible_processor | first }}"

3
尝试以下通用方法来处理此情况:
参考:在Ansible中的Jinja2模板中获取列表的前n个元素
# from list
- debug:
    msg: "First item: {{ ansible_processor[0] }}"
# from output, like 'https://xxx.xx/xxx/xxx.git'
- debug:
    msg: "git repo's name: {{ (item| urlsplit('path')| basename | splitext)[0] }}"

3

使用first过滤器:

first是一个Jinja2过滤器,用于获取数组(也称为列表)中的第一个值。last过滤器可用于返回数组中的最后一个值。

- debug:
    msg: "First item in the list: {{ ansible_processor | first }}"
  when: ansible_processor is defined

使用数组索引:

- debug:
    msg: "First item in the list: {{ ansible_processor[0] }}"
  when: ansible_processor is defined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接