模板

时间:2015-10-20 09:06:43

标签: ansible ansible-template

template/file.cfg.j2

此模板文件将包含将在三个框之间共享的基本行。每个方框的线条都会有一些差异。这是我想改变的值:ize。

set system user nsroot 546426471446579744 -encrypted

546 ... hash现在应该在{{ }}变量中,因为它们在实例之间会有所不同。 {{ item.hash}}

我需要一种方法来设置和构建,我需要include_vars等。

编辑:我拥有的内容:

vars/vars.yml

servers
   ns:
     - name: Copy hash
       hash: 187f637f107bf7265069ace04bf87fcd8e63923169a2c529a

playbook.yml

  tasks:
    - name: Variable:ize
      template: src=templates/template.j2 dest=/tmp mode=644 owner=root group=wheel
      with_items: servers[ansible_hostname]

1 个答案:

答案 0 :(得分:2)

在您的广告资源文件中,您需要执行以下操作:

host1 nsroot_hash=12345
host2 nsroot_hash=54321
host3 nsroot_hash=24680

然后你的template / file.cfg.j2将如下所示:

set system user nsroot {{ nsroot_hash }} -encrypted

编辑:您希望在库存文件中定义hash变量,因为您要为将要运行此任务的每个主机使用不同的值。因此,您的inventory(host_vars)文件应如下所示(我假设ns是您的某个服务器的名称):

ns hash=187f637f107bf7265069ace04bf87fcd8e63923169a2c529a

然后你的playbook.yml看起来就像这样:

- hosts: all
  tasks:
    - name: Variable:ize
      template: src=templates/template.j2 dest=/tmp/template.txt mode=644 owner=root group=wheel

请注意,您不需要with_items语句。在上面的例子中,假设ns是主机的名称,那么这将创建文件/tmp/template.txt,其中包含模板文本。 (请注意,dest是文件的路径,而不仅仅是目录的路径。)

如果您要将此任务应用于多个主机,那么您只需编辑清单文件,如上所示:

ns hash=187f637f107bf7265069ace04bf87fcd8e63923169a2c529a
aa hash=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bb hash=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

当您运行上面的playbook.yml文件时,它会将模板应用于所有三个主机ns,aa和bb,并将正确的哈希值放在每个主机上的文件中。

相关问题