从 ansible lineinfile 模块向文件添加命令输出

Add a command output to a file from ansible lineinfile module

我正在尝试编写一个 ansible 任务以将以下命令的输出合并到 /etc/lvm/lvm.conf 文件中:

[root@ansible]# vgs --noheadings -o vg_name
  my_vg        
  rhel_home
  rhel_root

上面提到的值需要添加如下:

volume_list = [ "rhel_root", "rhel_home", "my_vg" ]

在托管节点中,上述参数如下:

# volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]

请帮助我继续前进,因为我被困在这里:

- name: Fetch the Volume group
  shell: "vgs --noheadings -o vg_name"
  register: vgs

- debug:
    msg: "{{ vgs.stdout }}"

- name: Line in file
  lineinfile:
    path: /tmp/lvm.conf
    regex: "volume_list = .*"
    line: "volume_list = [ vgs.stdout_lines ]"

添加如下一行,vg名称不带双引号: volume_list = [ vgs.stdout_lines ] 在底部而不是替换下面的行:

volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]

需要帮助才能获得输出 volume_list = [ "rhel_root", "rhel_home", "my_vg" ]

为了您的目的,您需要在 lineinfile 任务中使用 {{ vgs.stdout_lines }} 列表(而不是 \"vgs.stdout_lines\" 字符串)变量。

喜欢:

line: "volume_list = {{ vgs.stdout_lines | to_json }}"

不过,我注意到命令返回的 VG 名称前面有空格,如 " rhel_root"。因此,set_fact 另一个具有不必要的空格 trimmed.

的变量可能是个好主意
    - command: vgs --noheadings -o vg_name
      register: vgs

    - set_fact:
        volume_list: "{{ volume_list | default([]) + [ item | trim ] }}"
      loop: "{{ vgs.stdout_lines }}"

    - lineinfile:
        path: /tmp/lvm.conf
        regexp: '# volume_list ='
        line: 'volume_list = {{ volume_list | to_json }}'