天天看点

ansible 远程获取变量 更新模板

ansible可使用template,设置变量,根据不同的环境,批量更新配置。

比如ip地址,每个部署环境可能都不同,不能写成固定值,

可使用如下方式,为每个机器自动更新配置,比如某个config.j2文件:

ipaddress={{ template_ip }}
           

通常,变量“template_ip”在执行ansible之前,就预先知道的,一般放在group_vars文件夹里面,

但是,对于某些值,是预先不知道的,或者是每台机器都不一样的,不能通过一个单一变量事先设定好,

比如某个配置文件要求写网卡的MAC地址,

    第1,每个机器的每个网卡都不一样;

    第2,ip地址可以人为分配,MAC地址取决于硬件,最好不要写死;

可以这样:

---
- hosts: sled-mcn0
  gather_facts: no
  tasks:
    - name: "test shell command result registe to be var"
      shell: ifconfig eth0 | grep ether | awk {'print $2'}
      register: macaddr_res

    - name: "show the mac addr"
      debug: var=macaddr_res.stdout

    - name: "template the config file"
      template: src=config.j2 dest=/etc/config.ini
           

在每台机器上执行一条shell命令,将结果取回来,作为变量macaddr_res,

再使用template更新本地config.j2的值,与mac地址相关的定义:

macaddr={{ macaddr_res.stdout }}
           

最后将配置文件更新到远端部署机上的/etc/config.ini

这只是一个最简单的"hello world"例子,

其实上面的shell命令中的"eth0"最好是通过group_vars变量设定,而不是固定写死为"eth0".

继续阅读