实例学习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.logls: cannot access /tmp/hello.log: No such file or directory[root@host31 ~]#
  
  
  • 1
  • 2
  • 3
 

执行playbook

[root@host31 ~]# ansible-playbook hello.playbookPLAY [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.loghello-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.playbookPLAY [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 ~]#

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值