Can I directly register the output of a command in ansible as a boolean?

Kit Sunde asked:

I have some code checking for the existence of something. If it has 2 lines it means the post exists. Can I register the variable from the check into a boolean immediately in the first task, rather than needing to cast it in the second? My current solution:

- name: Check if home page has been created
  sudo_user: www-data
  shell: wp post list --post_type=page --post_title=Home --post_status=publish
  register: is_homepage_created

- name: Booleanize homepage check
    is_homepage_created={{is_homepage_created.stdout_lines|length >= 2}}

My answer:

After some playing around with wp, I could not get it to actually filter output on post title. It always displayed a list of every page. This may not be relevant to you, but it might.

Given this apparent bug, I’d rewrite the play as follows:

First, have wp output in CSV format, which will be easier to work with. Then check whether the desired output appears within it. In the CSV format, if a page named Home exists, then the string ,Home, will be in the output, and should not match anything else, so that is what we will look for.

- name: Get list of WordPress pages
  sudo_user: www-data
  command: wp post list --post_type=page --post_title=Home --post_status=publish --format=csv
  register: wordpress_pages

- name: Create the homepage if it doesn't exist
  sudo_user: www-data
  command: wp post create --post_type=page --post_title=Home --porcelain
  when: "',Home,' not in wordpress_pages.stdout"

Finally, it’s best practice to use command instead of shell unless you really absolutely need to pass the command through a shell.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.