如何解决ansible-读取文件,然后随机选择条目
我正在使用Ansible 2.9.10。我正在尝试读取其中包含项目列表的文件。然后,我想从此列表中选择3个随机项目。我已经尝试了几种方法(在下面指出),但是似乎无法弄清楚。 文件itemList是项目列表,每行一个:
hammer
saw
wood
.....
在剧本中,我有:
vars:
file_contents: "{{ lookup('file','itemList') }}"
# Printing file contents returns "widget\hammer\nsaw\nwood"..... etc.
- name: Print file contents
debug:
msg: "File contents are {{ file_contents }}"
# Now try to select one random item from file_contents
- name: Select one random item
debug:
msg: "item is {{ item }}"
with_random_choice: "{{ file_contents }}"
我想念什么?似乎我正在变得比看起来更难。 TIA
解决方法
您将file_contents
作为1行,如下所示:
"msg": "File contents are hammer\nsaw\nwood\npencil\nfork\nspoon\nmobile"
这是1个项目,而不是项目列表(因为未识别行尾字符,并以'\ n'的字符串序列表示。
一个简单的调整就是使用'\ n'分隔符分割1行字符串。直接修改上一个任务,可以使用:
# Now try to select one random item from file_contents
- name: Select one random item
debug:
msg: "item is {{ item }}"
with_random_choice: "{{ file_contents.split('\n') }}"
欢呼
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。