How to get the first element of a list from the output of setup module in Ansible?

▼魔方 西西 提交于 2019-12-17 07:42:34

问题


I received the following data from the setup module:

"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,

I want to retrieve the 1st value of ansible_processor and use it in a Jinja2 template.

If I use {{ ansible_processor }}, it's giving me both values:

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

But I want only the first one.


回答1:


To get first item of the list:

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

Or:

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



回答2:


Try this for common handle this situation:

Ref: get-first-n-elements-of-a-list-in-jinja2-template-in-ansible

# 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] }}"


来源:https://stackoverflow.com/questions/41610207/how-to-get-the-first-element-of-a-list-from-the-output-of-setup-module-in-ansibl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!