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

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 ~]#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

事前确认

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

执行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 ~]#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

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

Ansible中使用环境变量

设定环境变量

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

输出环境变量中有的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 ~]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

执行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 ~]#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net

猜你喜欢

转载自www.cnblogs.com/firsttry/p/10135166.html