59

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
thinkingmonster
  • 5,063
  • 8
  • 35
  • 57

3 Answers3

119

To get first item of the list:

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

Or:

- debug:
    msg: "First item: {{ ansible_processor | first }}"
techraf
  • 64,883
  • 27
  • 193
  • 198
3

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] }}"
Cheney
  • 960
  • 8
  • 23
3

Using first filter:

first is a Jinja2 filter, used to get the first value in an array (also known as a list). The last filter can be used to return the last value in an array.

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

Using the array index:

- debug:
    msg: "First item in the list: {{ ansible_processor[0] }}"
  when: ansible_processor is defined
samnoon
  • 1,340
  • 2
  • 13
  • 23