首页 » 翻译 » Ansible 入门 » 正文

ansible 入门教程08 变量注册

我们可以把结果注册到我们的定义的标量中,然后在play执行过程中去使用这些变量

例如:

– hosts: web_servers

tasks:

– shell: /usr/bin/foo register: foo_result ignore_errors: True – shell: /usr/bin/bar when: foo_result.rc == 5

然后系统内置了一些变量来获取其他机器的信息,如:

常用的有:hostvars,group_names,groups

hostvars 就是其他机器的facts变量,当然这个其他主机必须是已经获取过一次变量信息了

group_names 是当前主机所有的所属group 列表

{% if ‘webserver’ in group_names %}
# some part of a configuration file that only applies to webservers
{% endif %}

groups是所有group的集合

{% for host in groups[‘app_servers’] %}
# something that applies to all app servers.
{% endfor %}

这个例子在配置双机热备啊,负载什么的时候挺有用的

获取指定分组下所有机器的ip地址:

{% for host in groups[‘app_servers’] %}

{{ hostvars[host][‘ansible_eth0′][‘ipv4′][‘address’] }}
{% endfor %}

这里有一个后边说到的例子,就是

– name: test play

hosts: all

tasks:

– shell: cat /etc/motd

register: motd_tontens

– shell: echo “mod contains the word hi”

when: motd_contents.stdout.find(‘hi’)!=-1
欢迎转载,转载请注明出处:http://www.503error.com/

Zhiming Zhang

Senior devops at Appannie
一个奔跑在运维路上的胖子
Zhiming Zhang

Latest posts by Zhiming Zhang (see all)

本文共 2 个回复

  • haff 2015/05/29 11:27

    这是要出书的节奏么

    • jaymz

      jaymz 博主 2015/05/29 15:04

      @ haff 好歹是做网站的,怎么不得弄一个自己的啊

Comments are closed.