在with_items中运行with_items

时间:2017-05-17 20:02:42

标签: ansible

我正在运行如下命令:

name: Generate a timed-based code for user
  command: "{{ item.command }} creates={{ item.file}}"
  with_items:
    - { command: '/usr/bin/google-authenticator -t -f -d --label=user1 --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/user1/.google_authenticator', file: '/home/user1/.google_authenticator' }
    - { command: '/usr/bin/google-authenticator -t -f -d --label=user2 --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/user2/.google_authenticator', file: '/home/user2/.google_authenticator' }

这很好但根本不是DRY

我正在尝试像这个角色做第二个with_items

- include_vars: main.yml

- name: Generate a timed-based code for user
  command: "{{ item.command }} creates={{ item.file }}"
  with_items:
    - { command: '/usr/bin/google-authenticator -t -f -d --label="{{ item.username }}" --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/"{{ item.username }}"/.google_authenticator', file: '/home/"{{{ item.username }}"/.google_authenticator' }
  with_items: "{{ users }}"
  become: true

内部vars/main.yml我有:

---

users:
  username: user1 
  username: user2 
  username: user3

在运行剧本时,我会看到:

[WARNING]: While constructing a mapping from /Users/bshutter/Dev/server/roles/googlemfa/tasks/main.yml, line 55, column 3, found a duplicate dict key (with_items). Using last
defined value only.

[WARNING]: While constructing a mapping from /Users/bshutter/Dev/server/roles/googlemfa/vars/main.yml, line 4, column 3, found a duplicate dict key (username). Using last defined
value only.

当它贯穿角色并进入任务Generate a timed-based code for user

TASK [googlemfa : Generate a timed-based code for user] **************************************
fatal: [10.1.10.36]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'file'\n\nThe error appears to have been in '/Users/bshutter/Dev/server/roles/googlemfa/tasks/main.yml': line 55, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Generate a timed-based code for user\n  ^ here\n"}

2 个答案:

答案 0 :(得分:2)

我不确定我是否完全理解您的问题,因为看起来您只有一种类型的命令可以运行。 所以,如果你真的只有google authenticator命令来运行,我会做这样的事情:

- name: Generate a timed-based code for user
  command: '/usr/bin/google-authenticator -t -f -d --label="{{item}}" --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/{{item}}' creates='/home/{{{ item }}/.google_authenticator'
  with_items: "{{ users }}"
  become: true

答案 1 :(得分:0)

您可能正在寻找with_nested

但是,使用创建选项很难实现,因为只有一个命令会创建该文件。另请注意,循环必须是不同的 - 您不能从另一个引用一个列表。