User Tools

Site Tools


docs:tips_n_tricks:ansible:shell.html

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
docs:tips_n_tricks:ansible:shell.html [25.11.2023 13:47 CET] – created peterdocs:tips_n_tricks:ansible:shell.html [25.11.2023 15:45 CET] (current) peter
Line 1: Line 1:
-====== Ansible - Calling shell scripts ====== +====== Ansible - shell scripts ====== 
-===== Task Template capable of check mode and reporting changed state =====+===== Task template capable of check mode and reporting changed state =====
 <note tip>This template assumes, that "CHANGED" and "FAILED" are on a line by itself, which isn't true if some other part of the script had some output not delimited by a newline</note> <note tip>This template assumes, that "CHANGED" and "FAILED" are on a line by itself, which isn't true if some other part of the script had some output not delimited by a newline</note>
 <code yaml roles/templates/tasks/shell1.yml> <code yaml roles/templates/tasks/shell1.yml>
-- name: You name it+- name: Shell scriptlet
   shell: |   shell: |
     if echo "Fake check for need of change - always true"     if echo "Fake check for need of change - always true"
Line 15: Line 15:
   check_mode: False   check_mode: False
   register: my_result   register: my_result
-  changed_when: 'CHANGED' in my_result.stdout_lines +  changed_when: "'CHANGED' in my_result.stdout_lines" 
-  failed_when: 'FAILED' in my_result.stderr_lines+  failed_when: "'FAILED' in my_result.stderr_lines
 +</code> 
 +===== Task template executing always - even in check mode - and failing on any output to stderr ===== 
 +This might be useful when using a script to gather information about the target host 
 +<code yaml roles/templates/tasks/shell2.yml> 
 +- name: Collect information 
 +  shell: | 
 +    echo '{"name": "Test", "msg": "Do the real thing here"}' ||  echo "FAILED" >&
 +  check_mode: False 
 +  register: last_result 
 +  changed_when: False 
 +  failed_when: "last_result.stderr_lines | length > 0" 
 + 
 +- name: Add to list if name does not exist 
 +  set_fact: 
 +    list_of_information: "{{ list_of_information + [ item ] }}" 
 +  loop: "{{ last_result.stdout_lines | from_json }}" 
 +  when: "item.name not in list_of_information | map(attribute='name')"
 </code> </code>
 {{tag>Ansible Shell}} {{tag>Ansible Shell}}
 {{entry>Ansible}} {{entry>Ansible}}
 {{entry>Shell}} {{entry>Shell}}
docs/tips_n_tricks/ansible/shell.html.1700916478.txt.gz · Last modified: 25.11.2023 13:47 CET by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki