我有一些期望在某些命令的输出中包含的字符串列表。如何创建一个 ansible 脚本来测试并在其中一个或多个条目不包含的情况下执行任务?
因此我的 ansible 脚本可能如下所示:
vars:
musthave:
- value1
- value2
tasks:
- name: Check the configured values
command: "cat configfile"
register: current_configuration
changed_when: false
- set a variable if one or more of the musthave's are missing in current_configuration.stdout
...
- name: Execute task to reconfigure system
command: "reconfigure..."
when: true = variable
那么有没有类似的东西
variable = false
for s in musthave:
if not s in current_configuration.stdout:
variable |= true
答案1
虽然使用建议的社区模块可能更容易解决问题,但我更喜欢不意味着要安装更多库的解决方案。以下是我想出的解决方案。
我最初的请求是检查命令输出中可能出现的特定值是否存在。准备一个列表来计算差异是一个缺点,但副作用是您可以计算两个方向上的差异。
所以现在我不仅可以检查缺失的条目,还可以检查过多的条目。
- name: print hostvars
debug:
var: hostvars[{{ ansible_host }}]['certificate_domains']
- name: print certificate
delegate_to: silver.fritz.box
command: "openssl x509 -in /home/hiran/homeserver.crt -noout -text"
register: certificate
- name: grab subject's common name and alternative names
set_fact:
commonName: "{{ certificate.stdout | regex_search('Subject.*CN\\s=\\s([\\.a-zA-Z]+)', '\\1') }}"
altNames: "{{ certificate.stdout | regex_findall('DNS:([\\.a-zA-Z]+)') }}"
- name: prepare the lists so they can be subtracted from each other
set_fact:
contained: "{{ (commonName + altNames) | unique }}"
musthave: "{{ hostvars[{{ ansible_host }}]['certificate_domains'] | unique }}"
- name: calculate differences
set_fact:
missing: "{{ musthave | difference(contained) }}"
toomuch: "{{ contained | difference(musthave) }}"
- name: show difference
debug:
msg: Something is wrong
when: (missing | length)>0 or (toomuch | length)>0