我必须读取文本文件中的每一行并将其添加到 yaml 中。这是我的游戏书
- hosts: localhost
tasks:
- name: Register a file content as a variable
ansible.builtin.shell: cat /home/packages.txt
register: result
- name: Print the transformed variable
ansible.builtin.debug:
msg: '{{ item }}'
loop: '{{ result.stdout | list }}'
- name: install
shell: yum install '{{ item }}'
loop: '{{ result.stdout | list }}'
packages.txt 包含
nginx
vim
grafana
当我运行此程序时,软件包未安装。这是控制台输出,
TASK [Register a file content as a variable] **********************************************************************************
changed: [localhost]
TASK [Print the transformed variable] *****************************************************************************************
TASK [install] ****************************************************************************************************************
PLAY RECAP ********************************************************************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0
要求是通过此 ansible playbook 从文本文件安装这些软件包
给定文件
shell> cat packages.txt
nginx
vim
grafana
在本地主机上,迭代列表。例如,下面的剧本
shell> cat test.yml
- hosts: localhost
tasks:
- name: install
package:
name: "{{ item }}"
loop: "{{ lookup('file', 'packages.txt').split() }}"
给出(删节,如果软件包已经安装)
TASK [install] *******************************************************
ok: [localhost] => (item=nginx)
ok: [localhost] => (item=vim)
ok: [localhost] => (item=grafana)
在远程主机上(查找仅在本地主机上有效),迭代stdout_lines,例如
- name: Register a file content as a variable
command: cat packages.txt
register: result
- name: install
package: "{{ item }}"
loop: "{{ result.stdout_lines }}"
如果您想避免使用 command 或 shell 模块,可以使用 fetch。例如,在下面的剧本中
shell> cat test.yml
- hosts: test_11
tasks:
- name: Create directory files
file:
state: directory
path: files
- name: Get file
fetch:
src: packages.txt
dest: files
- name: install
package:
name: "{{ item }}"
loop: "{{ lookup('file', path).split('\n') }}"
vars:
path: 'files/{{ inventory_hostname }}/packages.txt'
创建目录 files 并首先从远程主机获取文件。这将创建文件
shell> cat files/test_11/packages.txt
nginx
vim
grafana
然后迭代文件中的行
TASK [install] ***************************************************
changed: [test_11] => (item=nginx)
changed: [test_11] => (item=vim)
changed: [test_11] => (item=grafana)