如何约束命令以基于事实运行,并将其输出保存到相同的变量?



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

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

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

这是剧本。简而言之,我应该能够在一个任务下结合Task1.1和Task2.1,但我正在努力做到这一点。

---
- 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

您可以模板化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('') }}"

最新更新