如何根据事实设置命令运行并将其输出保存到同一个变量

问题描述 投票:0回答:1

下面剧本的目的是从许多设备中提取事实并使用它来运行特定的 shell 命令。除了两个例外,我相信我已经弄明白了大部分内容。

  1. 如何基于
    when
    语句运行一组命令与另一组命令?现在,我将第二组命令列在具有
    when
    条件的不同任务下,它们都可以工作,但第二个任务最终会覆盖 Jinja2 模板用于输出文件的寄存器。
  2. 如何使用相同的寄存器/变量来保存两个命令的输出而不覆盖
    register

我怀疑对两个命令使用相同的任务是关键,但我不知道如何实现这一点。

这是剧本。

---
- name: Gather facts (f5)
  bigip_device_info:
    provider: "{{ provider }}"
    gather_subset:
      - system-info
      - devices
  register: dev_fact



####################### LTM Hosts ###############################
- name: Task1.1 - Find vcmp count info
  shell: tmsh show vcmp health module-provision | grep 'ltm  nominal' | grep ltm | wc -l
  when: not ( 'Z100'in dev_fact['system_info']['platform'] or 'Z101' in dev_fact['system_info']['platform'] )
  ignore_errors: yes
  register: nommodltm
  failed_when: "'unexpected' in nommodltm.stdout"


- name: "Set Fact for Nominal Module Count for LTM"
  set_fact: nommodltm={{ nommodltm.stdout_lines[0] }}
  ignore_errors: yes

- name: Print lic info - vCMP Devices
  debug: 
    msg: Lic LTM Nominal Info={{ nommodltm }}

####################### LTM VE | Guests ###############################

- name: Task2.1 - Find vcmp count info
  shell: tmsh list sys provision | grep -b1 nominal | grep "sys provision ltm" | wc -l
  when: ( 'Z100'in dev_fact['system_info']['platform'] or 'Z101' in dev_fact['system_info']['platform'] )

  ignore_errors: yes
  register: nommodltm
  failed_when: "'unexpected' in nommodltm.stdout"

- name: "Set Fact for Nominal Module Count for LTM"
  set_fact: nommodltm={{ nommodltm.stdout_lines[0] }}
  ignore_errors: yes

- name: Print device info - vCMP Devices
  debug: 
    msg: Lic LTM Nominal Info={{ nommodltm }}


- name: Copy output to file
  template:
    src: invchktest.txt.j2
    dest: "inventory_check/{{ date }}-{{ dc }}-inventory_check.csv"
  delegate_to: localhost
  ignore_errors: true
printing ansible conditional-statements var ansible-template
1个回答
0
投票

您可以实际模板化您的

shell
命令并使用 Jinja 条件来运行一个或另一个命令,而不是使用
when

- name: Find vcmp count info
  shell: >-
    {%- if 'Z100' in dev_fact.system_info.platform 
          or 'Z101' in dev_fact.system_info.platform 
    -%}
      tmsh list sys provision \
        | grep -b1 nominal \
        | grep "sys provision ltm" \
        | wc -l
    {%- else -%}
      tmsh show vcmp health module-provision \
        | grep 'ltm  nominal' \
        | grep ltm \
        | wc -l
    {%- endif -%}
  register: nommodltm
  failed_when: "'unexpected' in nommodltm.stdout"

- name: Print device info - vCMP Devices
  debug: 
    msg: "Lic LTM Nominal Info: {{ nommodltm.stdout_lines[0] | default('') }}"
© www.soinside.com 2019 - 2024. All rights reserved.