This playbook aims to verify if a specific file exists in a specific directory and, if not, to create it. Neither the file nor the directory may exist before the verification. After the process is finished, I would like to have a statement that ell me that the file exists. See what I came up with and please give me feedback for clearer and smooth code.

I defined the host and the roles in the tree, so I am referring only to the tasks.

- name: Checking if processed_sms directory exists if it doesn't create it.
    path: "/home/pi/sms_service/processed_sms"
    state: directory

- name: Checking if place_holder.txt exists if it doesn't create it.
    path: "/home/pi/processed_sms/place_holder.txt"
    state: touch
  register: is_place_holder_exists

- name: printing message if place_holder.txt file exists
    msg: "place_holder.txt file exists"
  when: is_place_holder_exists.dest == "/home/pi/sms_service/processed_sms/place_holder.txt"

  • \$\begingroup\$ The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see How to get the best value out of Code Review: Asking Questions for guidance on writing good question titles. \$\endgroup\$ Commented Sep 21, 2021 at 8:43

1 Answer 1


So the goal of Ansible is, usually, idempotence. That is the whole point and intent with most of the Ansible modules. Ansible also uses declarative yaml, which is a fancy way of saying "describe the end-state, the engine will try to achieve it."

For what you have written, a production yaml playbook would probably say something more like:

- name: Create 'processed_sms' directory
    path: "/home/pi/sms_service/processed_sms"
    state: directory
- name: Create 'placeholder.txt'
  blah: ...
- name: Print activity message
  debug: ...

For the first task, the concept that the engine will check for the presence and create it if missing is implied and the whole point of using Ansible.

Your task names imply you are adding some conditional logic (Check for X, do Y if true). While that is technically what is happening, it's implied that Ansible will always do that because of the declarative and idempotent nature of Ansible automation.

The only syntax issue: your first task is missing a colon after "file". Any decent linter or IDE will catch this.

So like I said, minor syntax aside you have written precisely what you said you wanted it to do, but your commentary is a bit verbose.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.