【问题标题】:ansible with_items with comma separated item.valuesansible with_items 用逗号分隔 item.values
【发布时间】:2018-10-11 22:09:04
【问题描述】:

我正在尝试以某种方式在 Ansible 中创建一个以逗号分隔的 item.values 的嵌套循环。 变量: - 我的资源 - {名称:'share1',id:'user1,user2,user3'} - {名称:'share2',id:'user4'}

- name: Create users files
  copy:
  dest: "/etc/vsftpd_users/{{ item.id }}"
  content: |
    local_root=/vol/{{ item.name }}
  with_items: 
  - "{{ my_resources.split(',') }}" 

我的期望应该如下,就像每个文件都在里面创建了适当的内容。

$ cat user1
share1

$ cat user2
share1

$ cat user4
share2

但是,使用上述脚本创建的文件如下所示

-rw-r--r-- 1 root root 22 Oct 11 08:15 [u'user1', u'user2', u'user3']
-rw-r--r-- 1 root root 29 Oct 11 08:15 [u'user4']

有没有办法解决这个问题?

【问题讨论】:

  • 重构你的数据。

标签: ansible


【解决方案1】:

可以使用loopsubelements lookup/query实现,2.5版本开始支持

- hosts: localhost
  vars:
    users:
      - name: 'share1'
        id: "{{'user1,user2,user3'.split(',')}}"
      - name: 'share2'
        id: "{{'user4'.split(',')}}"

  tasks:
  - name: Create users file with content
    copy:
      dest: "/etc/vsftpd_users/{{ item.1 }}"
      content: |
        local_root=/vol/{{ item.0.name }}
    loop: "{{lookup('subelements', users, 'id', skip_missing=True)}}"

【讨论】:

  • 这很好用@Ignacio。非常感谢。请根据您共享的链接将loop 更新为with_list。使用loop 出现错误。
  • 不客气!这可能会发生,因为您的 ansible 版本,循环是 2.5 版的新功能
【解决方案2】:

Ansible 不能在没有脚本的情况下处理过于复杂的数据结构; 为方便起见,您应将用户数据重组为具有单个 id 的 dict 列表,例如:

- name: Create users file with content
  copy:
  dest: "/etc/vsftpd_users/{{ item.id }}"
  content: |
    local_root=/vol/{{ item.name }}
  with_items:
  - { name: 'share1', id: 'user1' }
  - { name: 'share1', id: 'user2' }
  - { name: 'share1', id: 'user3' }
  - { name: 'share2', id: 'user4' }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
相关资源
最近更新 更多