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
I am using the following approach, using only a grep -q
and a registered variable.
Upside is that it's simple, downside is that you have a FAILED
line in your output. YMMV.
- name: Check whether foobar is defined in /bar/baz
command:
cmd: 'grep -q foobar /bar/baz'
register: foobar_in_barbaz
changed_when: false
ignore_errors: true
- when: not foobar_in_barbaz.failed
name: Do something when foobar is in /bar/baz
....
- when: foobar_in_barbaz.failed
pause:
seconds: 1
content: |
You do not seem to have a foobar line in /bar/baz
If you add it, then magic stuff will happen!
If you want to fail if there is no user:
tasks:
- shell: grep username /etc/passwd
changed_when: false
By default shell
module will fail if command exit code is non zero.
So it will give you ok
if username is there and fails otherwise.
I use changed_when: false
to prevent changed
state when grepping.
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.
I'd probably register and evaluate a variable.
The following simple playbook works for me:
- hosts: localhost
tasks:
- name: read the passwd file
shell: cat /etc/passwd
register: user_accts
- name: a task that only happens if the user exists
when: user_accts.stdout.find('hillsy') != -1
debug: msg="user hillsy exists"