Skip to content

Instantly share code, notes, and snippets.

@jeevanshu
Last active October 2, 2022 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeevanshu/a5e0b6e7ee2ff53a55608ca7eca014de to your computer and use it in GitHub Desktop.
Save jeevanshu/a5e0b6e7ee2ff53a55608ca7eca014de to your computer and use it in GitHub Desktop.
Ansible setting env variables in host

Environment variables in Ansible

You can use following methodes to set env variables directly inside hosts

  1. lineinfile

     tasks:
       - name: Set env variable
         lineinfile:
           path: {{ user_bashrc_path }}/.bashrc
           line: export MY_VAR=test
       - name: Test env variable
         shell: . {{ user_bashrc_path }}/.bashrc && echo $MY_VAR
         register: mytestenv
       - debug: var=mytestenv
    
  2. blockinfile

     tasks:
       - name: Set env variables
         blockinfile:
           dest: {{ user_bashrc_path }}/.bashrc
           block: |
             export {{ item.name }}={{ item.line }}
           marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
           with_items:
             - { name: test1, line: hello1 }
             - { name: test2, line: hello2 }
             - { name: test3, line: hello3 }
       - name: Test env
         shell: . {{ user_bashrc_path }}/.bashrc && echo $test1
         register: mytestenv
       - debug: var=mytestenv
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment