ansible - select 列表中的多个随机名称

ansible - select multiple number of random names from list

我正在使用 ansible 2.10,并且有一个包含 14 个名称列表的变量。从这个列表中,我想分配一个随机数(从 9-14)的名字并将其写入一个文本文件。我正在为如何在 ansible 中执行此操作而苦苦挣扎。到目前为止,有这个:

in default.yml:
  randomNames: 'chad', 'bob', 'alice'.....

 - name: Define random number
   set_fact:
     numberNames:  "{{ range(9,14) }} | random }}"

 - name: Add random names to file
   lineinfile:
     src: {{ randomNames }}
     dest: namesList.txt
   loop:
      "{{ numberNames }}"

但我收到错误消息“传递给 'loop' 的数据无效,它需要一个列表。我知道这不是正确的方法,但有人可以帮我弄清楚什么是最好的方法是什么?

我应该补充一下我还需要名字,每行一个:

   bob
   alice
   ted
   ....

这里有多个问题。首先,这不是列表:

randomNames: 'chad', 'bob', 'alice'

那只是一个字符串。如果你想要一个列表,写:

randomNames: [chad, bob, alice]

或:

randomNames:
  - chad
  - bob
  - alice

(我去掉了引号,因为它们不是必需的,但如果您愿意,您可以写 'chad' 而不是 chad,等等)。


第二,这个任务...

- name: Define random number
  set_fact:
    numberNames:  "{{ range(9,14) }} | random }}"

...不生成列表;它 returns 一个数字。所以在后续任务中,当你写:

- name: Add random names to file
  lineinfile:
    src: {{ randomNames }}
    dest: namesList.txt
  loop: "{{ numberNames }}"

您正在尝试循环类似值 10.

的内容

最后,lineinfile 模块没有 src 参数。

如果您的目标是将 N 个随机名称写入文件,您可能需要 shuffle 过滤器,它随机化一个列表:

- hosts: localhost
  gather_facts: false
  vars:
    "randomNames": [
      "Bob", "Alice", "James", "Robert", "John", "Michael", "David", "William", "Richard",
      "Joseph", "Thomas", "Charles", "Christopher", "Daniel", "Matthew", "Anthony", "Mark",
      "Donald", "Steven", "Paul", "Andrew", "Joshua", "Mary", "Patricia", "Jennifer",
      "Linda", "Elizabeth", "Barbara", "Susan", "Jessica", "Sarah", "Karen", "Lisa",
      "Nancy", "Betty", "Margaret", "Sandra", "Ashley", "Kimberly", "Emily", "Donna",
      "Michelle"]

  tasks:
    - name: Define random number
      set_fact:
        numberNames: "{{ range(9,14) | random }}"

    - name: Add a random name to a file
      lineinfile:
        path: namesList.txt
        line: "{{ item }}"
      loop: "{{ (randomNames|shuffle)[:numberNames|int] }}"