The other day I was confronted with a bit of a problem in Ansible: I have a role with a docker_container
where I use two variables, one defining the user (role_user
) and one defining the group (role_group
). When both the user and group are defined, they specify the UID and GID respectively. If only the user is defined, then it can be either the UID, or the user name. If neither are defined, then they should be omitted altogether. If only the group is defined, then it's an invalid configuration and should throw an error.
I worked my poor neuron for a few days to see how to define this in a better way, and I come up with the following combination:
- In
defaults/main.yml
--- combo_user: combo_group:
- In
tasks/main.yml
--- ## tasks file for playground/combovars - name: Set combo variable set_fact: combo_uid: '{% if combo_user and combo_group %}{{combo_user}}:{{combo_group}}{% elif combo_user and not combo_group %}{{combo_user}}{% else %}error{%endif%}' - name: Show the variable ansible.builtin.debug: msg: System [{{ combo_uid }}]
While this is a proof of concept and doesn't cover all cases, you can see where I'm getting at:
- The
set_fact
sets a new variable - The variable's content is defined via an inline jinja template:
- If both variables are defined, the the result is
{{combo_user}}:{{combo_group}}
- If only the user is defined, then the result is
{{combo_user}}
- Otherwise, the variable is set to error (text)
- If both variables are defined, the the result is
As next steps, I need to add the default(omit)
behaviour in ansible and define the second (group-level) variable si I can use them in docker_container's user
or in its environment PID
/GID
.
HTH,
Member discussion: