Search code examples
variablesansiblejinja2

How can I find the user ID using ansible and use that in a jinja2 template?


I have to create a number of users using ansible. I pass the users as a list inside my ansible play in the vars section:

  vars:
    users: ['user1', 'user2']

I then have to create a script that uses this users' ID as an argument. The command inside the script is something like this:

blobfuse $1 --tmp-path=/mnt/resource/{{ item }}/ -o attr_timeout=240 -o entry_timeout=240 -o negative_timeout=120 -o uid=$USER_ID -o allow_other --container-name={{ item }} --file-cache-timeout-in-seconds=120 --config-file=/root/connection-{{ item }}.cfg

Everything works fine, with the exception of uid= I have tried with the lookup's pipe plugin but this doesn't get me the correct UID:

{{ lookup('pipe', 'grep -w {{ item }} /etc/passwd | cut -d : -f3') }}

My end goal is to get the UID of each of the created users, and pass that to the blobfuse command above.


Solution

  • What about using id command and subshell? You can then do something like

    blobfuse $1 --tmp-path=/mnt/resource/{{ item }}/ -o attr_timeout=240 -o entry_timeout=240 -o negative_timeout=120 -o uid="$(id {{ item }})" -o allow_other --container-name={{ item }} --file-cache-timeout-in-seconds=120 --config-file=/root/connection-{{ item }}.cfg

    If you are using command module - you'll have to replace it with shell.

    Edit: If you are using templates and want to use lookup plugin, which seems cleaner, you can do something like this (this was tested on local linux machine):

    template.yaml

    {% for item in users %}
    {{ item }} {{ lookup('pipe', "id -u " + item) }}
    {% endfor %}
    

    ansible command

    ansible -m template -i localhost, all -c local -a "src=template.yaml dest=result.txt" -e "{ users: [nobody,root]}"

    result.txt

    nobody 65534
    root 0
    

    In your case the error was using the {{ item }} in lookup, you should use just variable names and concatenation inside {{}} block