【问题标题】:Add a command output to a file from ansible lineinfile module从 ansible lineinfile 模块向文件添加命令输出
【发布时间】:2022-01-20 07:36:19
【问题描述】:

我正在尝试编写一个 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" ]

【问题讨论】:

  • 您应该查看vgs.stdout_lines,因为这是命令返回的 VG 名称列表
  • 我尝试了以下任务:``` - name: Line in file lineinfile: path: /tmp/lvm.conf regex: "# volume_list = .*" line: "\tvolume_list = [ \" vgs.stdout_lines\" ]" ``` 但没有运气

标签: module ansible


【解决方案1】:

出于您的目的,您需要在您的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 }}'

【讨论】:

  • 感谢您的支持,我需要稍微修改一下预期的输出将在列表中的第一项和最后一项之前和之后有空格,如下所示[“rhel_root”,“rhel_home”,“my_vg”]但我们会变成这样 ["rhel_root", "rhel_home", "my_vg"]
  • 尝试了以下一个但仍然无法在列表前后添加空格:“volume_list = {{ ' '+ volume_list | to_json +' ' }}”
  • 空格不应该是强制的,不知道没有空格配置不行吗?
  • 谢谢,正如你所说的,空间是不必要的。
猜你喜欢
  • 2019-06-03
  • 2020-09-09
  • 2022-07-04
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
相关资源
最近更新 更多