文章目录
一、注册和定义变量方式
1、命令行传递
在-e后接参数名和参数值
[root@ansible_center tmp]# ansible test -m shell -a "echo {
{ say_hi }}" -e 'say_hi="hello world"'
192.168.189.134 | CHANGED | rc=0 >>
hello world
2、在playbook中vars中定义
[root@ansible_center tmp]# cat test.yaml
---
- hosts: 192.168.189.134
vars:
var1: value1
var2: value2
tasks:
- debug: msg="{
{
var1 }}{
{
var2 }}"
vars:
var2: value2.2
[root@ansible_center tmp]# ansible-playbook test.yaml
PLAY [192.168.189.134] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.189.134]
TASK [debug] *******************************************************************
ok: [192.168.189.134] => {
"msg": "value1value2.2"
}
PLAY RECAP *********************************************************************
192.168.189.134 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
注意:debug这个任务调用var2的时候,var2的值为在当前任务下定义的那个值。这里的作用域和编程中局部变量和全局变量的原理是一样的
3、register注册
[root@ansible_center tmp]# cat test.yaml
---
- hosts: 192.168.189.134
tasks:
- shell: echo haha
register: say_hi
- debug: var=say_hi.stdout
[root@ansible_center tmp]# ansible-playbook test.yaml
PLAY [192.168.189.134] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.189.134]
TASK [shell] *******************************************************************
changed: [192.168.189.134]
TASK [debug] *******************************************************************
ok: [192.168.189.134] => {
"say_hi.stdout": "haha"
}
PLAY RECAP *********************************************************************
192.168.189.134 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
解释:这里的register把模块执行后的结果赋值给say_hi
4、set_fact定义
set_fact
模块可以自定义facts,这些自定义的facts可以通过template或者变量的方式在playbook中使用。
[root@ansible_center tmp]# cat test.yaml
---
- hosts: 192.168.189.134