ansible中的group_names变量

NAN*_*NIS 4 ansible ansible-inventory

当我执行这个剧本时,我遇到了一些问题:

- hosts: all
  connection: local
  tasks:
  - template: src=/etc/ansible/{{group_names}}/common.j2 dest=/etc/ansible/configs/{{inventory_hostname}}.txt
    name: create common config snippets
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

fatal: [R1]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to find '/etc/ansible/[u'ios']/common.j2' in expected paths."}
fatal: [R2]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to find '/etc/ansible/[u'ios1']/common.j2' in expected paths."}
Run Code Online (Sandbox Code Playgroud)

这是我的小组:

/etc/ansible# cat hosts | grep ios           
[ios]
[ios1]
Run Code Online (Sandbox Code Playgroud)

这是我的common.j2文件:

/etc/ansible# ls ios1/
common.j2


/etc/ansible# ls ios/ 
common.j2
Run Code Online (Sandbox Code Playgroud)

有人可以详细说明为什么group_names退货[u'group_names]吗?

tec*_*raf 8

因为group_names列表(这就是它被包围的原因[ ])——一个主机可以属于多个组。

您需要决定您的目标是什么:

  • 如果您想包含所有组的文件,则必须添加一个循环:

    - hosts: all
      connection: local
      tasks:
        - name: create common config snippets
          template:
            src: /etc/ansible/{{item}}/common.j2
            dest: /etc/ansible/configs/{{inventory_hostname}}.txt
          with_items: "{{group_names}}"
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果您想添加单个组,您可以引用单个元素 ( group_names[0]),但这似乎不实用......