Setting Environment Variables for Managed Nodes in Ansible
Ansible Playbook sets variables for managed hosts through <span>environment</span>.
- name: test environment
hosts: all
become: true
gather_facts: true
environment:
test_path: testpath
PATH: "/usr/local/custon_software/bin/:{{ ansible_env.PATH }}"
tasks:
- name: get env
ansible.builtin.shell: /bin/env
register: shell_result
- name: print env
ansible.builtin.debug:
var: shell_result.stdout_lines
In this example, Ansible adds a <span>test_path=testpath</span> variable to the managed host and modifies the <span>PATH</span> variable to <span>/usr/local/custon_software/bin/:$PATH</span>.
Setting Default Values for Modules in Ansible
If a module is frequently called, Ansible can set default values for the module using <span>module_defaults</span> to improve efficiency.
- hosts: localhost
module_defaults:
ansible.builtin.file:
owner: root
group: root
mode: 0755
tasks:
- name: Create file1
ansible.builtin.file:
state: touch
path: /tmp/file1
- name: Create file2
ansible.builtin.file:
state: touch
path: /tmp/file2
- name: Create file3
ansible.builtin.file:
state: touch
path: /tmp/file3
<span>module_defaults</span>can be used at the Playbook, block, and tasks level.Parameter values specified in tasks will override the default values.
Default values can be removed using an empty dictionary:
- name: Create file1
ansible.builtin.file:
state: touch
path: /tmp/file1
module_defaults:
file: {}
Setting default values may lead to unexpected issues, such as affecting the execution of tasks involving dynamic imports and static imports.
For more information, visit: https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_module_defaults.html.