How do I get Ansible to load /snap/bin? I've tried everything, can't get it to work

tl;dr: How do I get my environment variables to load with /snap/bin added?

Here’s a test block that I added to my playbook to try and add /snap/bin to my PATH, which I want Ansible to load thereafter. I’ve seen this recommendation on a number of different forums; stack overflow, reddit, etc. Am I doing something wrong or is there a better approach to achieve this?

- name: Test path
  tags: test-path
  vars:
    path_var: "/snap/bin"
  block:
    - name: Add a path to system-wide $PATH.
      ansible.builtin.copy:
        dest: /etc/profile.d/custom-path.sh
        content: 'PATH=$PATH:{{ path_var }}'
        mode: "0644"

    - name: Dump path
      ansible.builtin.command: echo $PATH
      register: path_output

    - name: Dump path output
      ansible.builtin.debug:
        var: path_output.stdout

And here’s the output:

--- before: /etc/profile.d/custom-path.sh
+++ after: /etc/profile.d/custom-path.sh
@@ -1 +1 @@
-export PATH=$PATH:/snap/bin
\ No newline at end of file
+PATH=$PATH:/snap/bin
"path_output.stdout": "/home/brad/.pyenv/versions/3.13.1/bin:/home/brad/.pyenv/libexec:/home/brad/.pyenv/plugins/python-build/bin:/home/brad/.pyenv/plugins/pyenv-virtualenv/bin:/home/brad/.pyenv/plugins/pyenv-update/bin:/home/brad/.pyenv/plugins/pyenv-doctor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

I’ve tried adding export as well, still doesn’t work. I have this working in ZSH no problems because the same code, with export, is in my .profile file. It seems like it’s strictly an issue with /bin/sh which I don’t understand since this setup seem to work for everyone else?

I’m on Raspbian Bookworm and host machine is MacOS running ansible [core 2.18.1] and Python 3.13.1

I’m also confused because I don’t see anyone else having to add this to PATH when I’m reading through other microceph ansible roles? Not sure why. (Update: these aren’t working either)

Here’s a few examples:

Try sourcing the profile – as far as I’m aware Ansible sets the ${PATH} itself, it doesn’t get it from /etc/profile:

    - name: Dump path
      ansible.builtin.shell: source /etc/profile && echo $PATH
      register: path_output

    - name: Dump path output
      ansible.builtin.debug:
        var: path_output.stdout

But perhaps I have misunderstood what you are trying to achieve?

Ansible does batch (non interactive) logins and executions, it also prefers /bin/sh over other shells unless you specifically configure that as the executable/shell plugin. As for environment, you can use the environment keyword Setting the remote environment — Ansible Community Documentation to add context to the task’s action’s execution

1 Like