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
chdir={{wordpress_path}}
register: is_homepage_created
- name: Booleanize homepage check
set_fact:
is_homepage_created={{is_homepage_created.stdout_lines|length >= 2}}
I don't think so, since you need to use
set_fact
to set it to anything other than its actual output, and I don't thinkshell
can return a boolean directly.I believe the usual way of doing this is to replicate the conditional you have in the "booleanize" task everywhere you use the fact, which is something you understandably want to avoid. Unfortunately, the register functionality is rather simple.
You could probably use a combination of
failed_when
andignore_errors: yes
to implement such functionality, but doing so would make a failure to run the shell command map to one boolean or the other, so I wouldn't recommend it.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 namedHome
exists, then the string,Home,
will be in the output, and should not match anything else, so that is what we will look for.Finally, it's best practice to use
command
instead ofshell
unless you really absolutely need to pass the command through a shell.You can use a lookup for this.
Playbook:
Output: