1. import_tasks 引用变量时,要确保变量定义在 vars/vars_file或命令行中,不能使用facts变量和inventory里面的变量
]# cat import_include.yml
- hosts: nfs
gather_facts: no
#vars:
# filename: test.yml
tasks:
- set_fact:
filename: test.yml
- import_tasks: "{{ filename }}"
- include_tasks: "{{ filename }}"
]# ansible-playbook import_include.yml
ERROR! Error when evaluating variable in import path: {{ filename }}.
When using static imports, ensure that any variables used in their names are defined in vars/vars_files
or extra-vars passed in from the command line. Static imports cannot use variables from facts or inventory
sources like group or host vars.
2.when 关键字对 include_tasks 和 import_tasks 有着本质区别
当对 import_tasks 使用 when 进行条件判断时,when 对应的条件会被应用于 include 文件中的每一个任务,意思是每要执行一个任务时,都要先进行条件判断。总结起来就是顺序执行 include 文件中列出的每一个任务前,都要进行条件判断,满足条件就执行,不满足就跳过,需要多次判断。
当对 include_tasks 使用 when 进行条件判断时,when 对应的条件只应用一次,发生在是否include这个文件,若include,则执行这个include文件中所有的任务,不再进行其他判断。下面的代码中,test1.yml中,打印finish的debug因为不满足条件num ==0,skipping跳过了。
]# cat when_import_include.yml
- hosts: nfs
gather_facts: no
tasks:
- name: "set num to 0"
set_fact:
num: 0
- include_tasks: test1.yml
when: num == 0
- name: "set num to 0"
set_fact:
num: 0
- import_tasks: test1.yml
when: num == 0
[root@m01 playbook]# cat test1.yml
- name: "set num to 1"
set_fact:
num: 1
- debug:
msg: "finish"
[root@m01 playbook]# ansible-playbook when_import_include.yml
PLAY [nfs] **********************************************************************************************************************************
TASK [set num to 0] *************************************************************************************************************************
ok: [172.16.1.31]
TASK [include_tasks] ************************************************************************************************************************
included: /server/scripts/ansible/playbook/test1.yml for 172.16.1.31
TASK [set num to 1] *************************************************************************************************************************
ok: [172.16.1.31]
TASK [debug] ********************************************************************************************************************************
ok: [172.16.1.31] => {
"msg": "finish"
}
TASK [set num to 0] *************************************************************************************************************************
ok: [172.16.1.31]
TASK [set num to 1] *************************************************************************************************************************
ok: [172.16.1.31]
TASK [debug] ********************************************************************************************************************************
skipping: [172.16.1.31]
PLAY RECAP **********************************************************************************************************************************
172.16.1.31 : ok=6 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0