Ansible 为被控节点设置环境变量
Ansible Playbook 通过 environment
设置被控主机的变量。
- 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
这个例子里,Ansible 为被控主机添加了一个 test_path=testpath
变量,并修改 PATH
变量为 /usr/local/custon_software/bin/:$PATH
。
Ansible 为模块设置默认值
如果某个模块经常被调用,Ansible 可以通过 module_defaults
设置模块默认值以提高使用效率。
- 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
module_defaults
可以在 Playbook、block 和 tasks 级别使用。在 tasks 中指定的参数值会覆盖默认值。
可以用空字典来删除之前的默认值:
- name: Create file1
ansible.builtin.file:
state: touch
path: /tmp/file1
module_defaults:
file: {}
设置默认值可能会造成意想不到的问题,比方说设置的默认值影响动态导入和静态导入的任务执行。
更多信息查看:https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_module_defaults.html。