Export An Env Var To Container With Ansible

ansible

I'd like to export an environment variable to Docker using Ansible (preferably) that has a value of a command substitution, e.g.

export SSH_AUTH_SOCK=`cat /root/file.txt`

file.txt's content changes from time to time, therefore I need the command substitution to dynamically change the var's value.

What is the way to achieve such thing ? I tried

env:
  SSH_AUTH_SOCK="`cat /root/file.txt`"

but it appended the literal string rather than its value.

Best Answer

You can use the pipe lookup plugin:

environment:
  SSH_AUTH_SOCK: "{{ lookup('pipe', 'cat /root/file.txt') }}"

Remember lookup plugins are executed locally on the control machine, not on the target server. If the target server if different, you need to register the value in a separate task, as the other answer suggests.

Note also that you should use YAML notation to declare the environment dictionary (and it's not env).