Reputation: 127
I'm trying to build a playbook that collects certain information from my hosts. So I'll just fire-up some shell commands and store their return values in a variable. Each command output (e.g. 'ls -la') shall be concaternated to the former so if all hosts were passed I'll get a complete list.
So this is my playbook:
---
- name: try to set variable
hosts: all
vars:
my_test_var: []
tasks:
- name: just get a simple list and show it
shell: ls -la
register: out
my_test_var: "{{ my_test_var + out.stdout }}"
- debug:
msg: "Listing of current dir: {{ my_test_var }}"
So first I create an empty list called: "my_test_var" and the first task should append its output from the "ls -la" command.
But it doesn't. Ansible just ignores the variable. But why ?!
[WARNING]: Ignoring invalid attribute: my_test_var
Upvotes: 0
Views: 1458
Reputation: 6685
there are a few issues with your playbook.
1:
- debug:
msg: "Listing of current dir: {{ my_test_var }}"
msg
needs one more indentation, you need to change to:
- debug:
msg: "Listing of current dir: {{ my_test_var }}"
2:
you cant get the output from ls -al and in the same task manipulate the my_test_var. you need to use seperate tasks. PLease see my playbook below about this.
3:
the out.stdout
variable is a string variable, while the my_test_var
is a list. if you want to add the whole out.stdout
to the list, you need to use this syntax:
my_test_var: "{{ my_test_var + [ out.stdout ] }}"
if your intention was to add the out.stdout_lines
(which is a list of each line of the ls -al output), your syntax is fine:
my_test_var: "{{ my_test_var + out.stdout_lines }}"
tip:
you dont need to "initialize" the my_test_var
variable to an empty list. you can use the default
filter by using:
my_test_var: "{{ my_test_var|default([]) + out.stdout_lines }}"
full playbook below:
---
- name: try to set variable
hosts: localhost
gather_facts: false
vars:
# my_test_var: []
tasks:
- name: just get a simple list and show it
shell: ls -la
register: out
- name: print out
debug:
var: out
- name: set the my_test_var to the output
set_fact:
my_test_var: "{{ my_test_var|default([]) + out.stdout_lines }}"
- debug:
var: my_test_var
Upvotes: 1