如何读取Ansible中多行变量的行数

How to read the number of lines in a multiline variable in Ansible

我将多行变量 dest_host 从 Jenkins 传递到 Ansible,如下所示

ansible-playbook -i allmwhosts.hosts action.yml -e '{ dest_host: myhost1
myhost2 }' --tags validate

在 ansible 中,我希望计算 dest_host 中存在的行数,在本例中为 2。

我可以想到command: "cat {{ dest_host }} | wc -l"注册输出然后打印的解决方案。但是,这些是在 Ansible 中获得它而不是使用 unix 命令的更好方法吗?

这就是 | length filter 的用途

- debug:
    msg: '{{ dest_host | length }}'
  vars:
    dest_host: "alpha\nbeta\n"

尽管预先警告您的 -e 由于 yaml 的标量折叠

没有按照您的想法(关于行)进行操作
ansible -e '{ bob:
  alpha
  beta
}' -m debug -a var=bob -c local -i localhost, localhost

发射 "bob": "alpha beta"

但是 | length 仍然可以通过使用 | split | length

来帮助您

请注意,并非所有结果都可以仅通过 | split | length 就可以很好地播放 — 例如,采用如下所示的 stdout

stdout:
  - "this is the first line\nthis is the second line"

如果您想计算行数,{{ stdout[0] | split | length }} 会给您类似 9 或 10 的结果,而不是 2 — 它以空格分隔!

因此,在这种情况下,您需要使用 {{ stdout[0].split('\n') | length }}(感谢 Python),这将使您 2 成为 intended/desired。