Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to nicely split on multiple lines long conditionals with OR on ansible?

I already know that if you have long conditionals with and between them you can use lists to split them on multiple lines.

Still, I am not aware of any solution for the case where you have OR between them.

Practical example from real life:

when: ansible_user_dir is not defined or ansible_python is not defined or ansible_processor_vcpus is not defined

This line is ugly and hard to read, and clearly would not fit a 79 column.

How can we rewrite it to make it easier to read?

like image 560
sorin Avatar asked Nov 01 '18 09:11

sorin


People also ask

How do you split in Ansible?

Split Lines in Ansible You can use the 'split()' function to divide a line into smaller parts. The output will be a list or dictionary. This is a Python function and not a Jinja2 filter. For example, in the below example, I am splitting the variable 'split_value' whenever a space character is seen.

What is stdout in Ansible?

By default Ansible sends output about plays, tasks, and module arguments to your screen (STDOUT) on the control node. If you want to capture Ansible output in a log, you have three options: To save Ansible output in a single log on the control node, set the log_path configuration file setting.


1 Answers

Use the YAML folding operator >

when: >
  ansible_user_dir is not defined or 
  ansible_python is not defined or 
  ansible_processor_vcpus is not defined

As the ansible documentation states:

Values can span multiple lines using | or >. Spanning multiple lines using a Literal Block Scalar | will include the newlines and any trailing spaces. Using a Folded Block Scalar > will fold newlines to spaces; it’s used to make what would otherwise be a very long line easier to read and edit. In either case the indentation will be ignored.

Additional info can be found here:

  • https://yaml-multiline.info/
  • https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
  • http://yaml.org/spec/1.2/spec.html#id2760844
like image 100
JGK Avatar answered Sep 18 '22 14:09

JGK