Ansible variable with find

155 views
Skip to first unread message

Anfield

unread,
Jun 27, 2017, 7:55:02 PM6/27/17
to Ansible Project
Running the playbook below and wondering whats the correct syntax so I can use a variable within the find statement below

This line is in question -
      when: p.stdout.find"{{('user')}}" != -1

This would be correct without a variable

when: p.stdout.find('daniel') != -1

How do I do this with a variable?

Playbook
- hosts: localhost
  become: yes
  vars:
    user: daniel
  tasks:
    - name: Create a new user on the server
      user:
        name: "{{user}}"
        state: present
    - name: Check to ensure the user has been created
      shell: cat /etc/passwd | grep "{{user}}"
      register: p
    - debug: msg="The user {{user}} exists"
      when: p.stdout.find"{{('user')}}" != -1
    - name: Create a file in the /opt folder called program1.sh
      command: touch program1.sh
      args:
        chdir: /opt
        creates: program1.sh

Kai Stian Olstad

unread,
Jun 28, 2017, 10:45:13 AM6/28/17
to ansible...@googlegroups.com
On 28. juni 2017 01:55, Anfield wrote:
> Running the playbook below and wondering whats the correct syntax so I can
> use a variable within the find statement below
>
> This line is in question -
> when: p.stdout.find"{{('user')}}" != -1
>
> This would be correct without a variable
>
> when: p.stdout.find('daniel') != -1
>
> How do I do this with a variable?

when: p.stdout.find(user) != -1


--
Kai Stian Olstad

Anfield

unread,
Jun 30, 2017, 3:03:15 PM6/30/17
to Ansible Project, ansible-pr...@olstad.com
Thanks! But how does it differentiate between just the text user, and the actual variable user? Or does it just know because user is defined as a variable at the top in the vars section?

I tried that out and it works well.


Kai Stian Olstad

unread,
Jun 30, 2017, 3:27:30 PM6/30/17
to ansible...@googlegroups.com
On 30. juni 2017 21:03, Anfield wrote:
> Thanks! But how does it differentiate between just the text user, and the
> actual variable user? Or does it just know because user is defined as a
> variable at the top in the vars section?

Text is indicated with single or double quote, so 'user' or "user".
When you don't use quotes it's taken as the variable user.

--
Kai Stian Olstad

Anfield

unread,
Jul 3, 2017, 11:58:51 AM7/3/17
to Ansible Project, ansible-pr...@olstad.com
Great explanation. Thanks

Reply all
Reply to author
Forward
0 new messages