【问题标题】:Ansible - to modify variablesAnsible - 修改变量
【发布时间】:2020-08-25 11:39:22
【问题描述】:

我正在尝试修改 ansible 变量中的值,如下所示:

- name: Store edited data in file
  shell: cat "{{ list }}" | tr -s ' ' | cut -d' ' -f3 | tr -d ',"' | tr -d ',"'
  register: filenew

其中 {{ list }} 类似于:

    "alertname": "KubePodCrashLooping",
    "alertname": "AlertmanagerReceiversNotConfigured",
    "alertname": "ImagePruningDisabled",
    "alertname": "CPUThrottlingHigh",
    

试图得到类似下面的东西,其中只显示名称:

KubePodCrashLooping
AlertmanagerReceiversNotConfigured
ImagePruningDisabled
CPUThrottlingHigh

【问题讨论】:

  • 您能否举例说明 {{ list }} 中的值和所需的输出?
  • 修改了数据。请检查。谢谢

标签: ansible yaml


【解决方案1】:

遍历列表,然后像这样修改每个项目:

- name: store edited data in file
  debug:
    msg: {{ item.split(":")[1].split('"')[1].split('"')[0]
  with_items: {{ list }}
  register: fileitem

【讨论】:

    【解决方案2】:

    鉴于数据存储在文件list.data 中,下面的任务将创建带有名称的列表lines_new。例如

        - set_fact:
            lines_new: "{{ lines_new|default([]) +
                           [item.split(':')[1][2:-2]] }}"
          loop: "{{ lookup('file', 'list.data').splitlines() }}"
        - debug:
            var: lines_new
    

    给予

      lines_new:
      - KubePodCrashLooping
      - AlertmanagerReceiversNotConfigured
      - ImagePruningDisabled
      - CPUThrottlingHigh
    

    在 Ansible 中创建文件的最佳实践是模块 template。例如,创建一个模板

    shel> cat filenew.j2 
    {% for item in lines_new %}
    {{ item }}
    {% endfor %}
    

    然后是任务

        - template:
            src: filenew.j2
            dest: filenew
    

    从模板filenew.j2创建文件filenew

    shell> cat filenew
    KubePodCrashLooping
    AlertmanagerReceiversNotConfigured
    ImagePruningDisabled
    CPUThrottlingHigh
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多