I got a shell task in ansible that plays between if-else
condition
Under if condition it prints echo
2 lines while in the else
condition it prints a single line.
I need a generic debug print statement that prints for both if
and else
condition.
- name: Extract certificate or key information
shell: >
if [[ "{{ certlocation }}" != *.key ]]; then
cert_cn=$(openssl x509 -in "{{ certlocation }}" -noout -subject -nameopt sep_multiline)
echo "~$cert_cn"
cert_san=$(openssl x509 -in "{{ certlocation }}" -noout -ext subjectAltName)
echo "~$cert_san"
else
cert_san=$(openssl x509 -in "{{ certlocation }}" -noout -ext subjectAltName)
echo "~$cert_san"
fi
register: cert_info
delegate_to: localhost
- name: Print specific information
debug:
msg: |
cert_cn: "{{ cert_info.stdout_lines[0].split('~')[1] | default('NA') }}"
cert_san: "{{ cert_info.stdout_lines[1].split('~')[1] | default(cert_info.stdout_lines[0].split('~')[1]) }}"
I tried the above but it fails with the below error during the else
condition which prints a single line:
TASK [Print specific informations] ***************************************************************************************************************************Monday 29 July 2024 23:51:46 -0500 (0:00:00.022) 0:00:00.517 ***********
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: list object has no element 1nnThe error appears to be in '/home/wladmin/teststdoutlines.yml': line 17, column 7, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nnn - name: Print lines using index from stdout_linesn ^ heren"}
I was expecting upon failure that it would default to cert_info.stdout_lines[0].split('~')[1]
which has a valid value.
Can you suggest how to handle such cases in ansible the right way?