【问题标题】:How to read the number of lines in a multiline variable in Ansible如何在 Ansible 中读取多行变量中的行数
【发布时间】:2021-06-16 15:04:54
【问题描述】:

我将一个多行变量 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 命令的更好方法吗?

【问题讨论】:

    标签: variables parameters count ansible multiline


    【解决方案1】:

    这就是| 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 来帮助您

    【讨论】:

    • {{ dest_host.split() | length }} 帮助解决了这个问题。你能更新你的答案吗?
    • 你的意思是我应该更新最后一句,它的字面意思是“通过使用| split | length”结尾?
    • 是的 @mdaniel as {{ dest_host | split | length }} 错误和 {{ dest_host.split() | length }} 有效
    • 这不是我的经验,否则我不会写它:ansible -e '{bob: alpha beta }' -m debug -a msg='{{ bob | split | length }}' -c local -i localhost, localhost -> "msg": "2" 所以我猜你的系统有问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多