实例学习ansible系列(14)playbook变量使用,ansibleplaybook


ansible的playbook中的变量引用使用{{ }}。同时本文也会给出实例确认如何使用环境变量降低Hardcoding的耦合。Ansbile还内嵌了七个很有用的变量,使用得当也会带来很大的便利。

  • hostvars变量
  • groups变量
  • group_names变量
  • inventory_hostname变量
  • inventory_hostname_short
  • inventory_dir
  • inventory_file

Ansible中使用变量实例

在vars后设定变量message,并将此message内容输出到log中

[root@host31 ~]# cat hello.playbook
- hosts: host31
  vars:
    - message: hello-world
  gather_facts: false
  tasks:
    - name:  say hello task
      shell: echo {{message}}  `date` by `hostname` >/tmp/hello.log
[root@host31 ~]#

事前确认

[root@host31 ~]# ll /tmp/hello.log
ls: cannot access /tmp/hello.log: No such file or directory
[root@host31 ~]#

执行playbook

[root@host31 ~]# ansible-playbook hello.playbook

PLAY [host31] ******************************************************************

TASK [say hello task] **********************************************************
changed: [host31]

PLAY RECAP *********************************************************************
host31                     : ok=1    changed=1    unreachable=0    failed=0

[root@host31 ~]#

执行结果确认,message变量的内容被正确输出到文件中了。

[root@host31 ~]# cat /tmp/hello.log
hello-world Sun Jul 31 04:26:23 EDT 2016 by host31
[root@host31 ~]#

Ansible中使用环境变量

设定环境变量

[root@host31 ~]# export MESSAGE="hello-world-ansible"

输出环境变量中有的HOSTNAME到log中

[root@host31 ~]# cat hello.playbook
- hosts: host31
  gather_facts: false
  tasks:
    - name:  say hello task
      shell: echo ${HOSTNAME}  `date` by `hostname` >/tmp/hello.log
[root@host31 ~]

执行playbook

[root@host31 ~]# ansible-playbook hello.playbook

PLAY [host31] ******************************************************************

TASK [say hello task] **********************************************************
changed: [host31]

PLAY RECAP *********************************************************************
host31                     : ok=1    changed=1    unreachable=0    failed=0

[root@host31 ~]#

确认结果的输出log
[root@host31 ~]# cat /tmp/hello.log
host31 Sun Jul 31 04:53:42 EDT 2016 by host31
[root@host31 ~]#

相关内容

    暂无相关文章