I'm very new to Ansible
Is it possible to check if a string exists in a file using Ansible.
I want to check is a user has access to a server. this can be done on the server using cat /etc/passwd | grep username
but I want Ansible to stop if the user is not there.
I have tried to use the lineinfile
but can't seem to get it to return.
code
- name: find lineinfile: dest=/etc/passwd regexp=[user] state=present line="user"
The code above adds user to the file if he is not there. All i want to do is check. I don't want to modify the file in any way, is this possible
Thanks.
There is no Ansible grep module, but you can use the grep commands along with shell module or command module. We can store the results of the task and use it in various conditional statements, print them or use them for debugging purposes.
backrefs. boolean. added in 1.1 of ansible.builtin. Used with state=present . If set, line can contain backreferences (both positional and named) that will get populated if the regexp matches.
It's a tricky one. the lineinfile module is specifically intended for modifying the content of a file, but you can use it for a validation check as well.
- name: find lineinfile: dest: /etc/passwd line: "user" check_mode: yes register: presence failed_when: presence.changed
check_mode
ensures it never updates the file. register
saves the variable as noted. failed_when
allows you to set the failure condition i.e. by adding the user because it was not found in the file.
There are multiple iterations of this that you can use based on what you want the behavior to be. lineinfile docs particular related to state
and regexp
should allow you to determine whether or not presence or absence is failure etc, or you can do the not presence.changed
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With