如何使用Ansible验证文件是否具有特定的子字符串?

时间:2015-03-19 22:27:40

标签: ansible ansible-playbook

我希望在我的Ansible游戏中有assertfail任务验证是否已部署正确的代码构建。部署附带一个version.properties文件,其中包含我关心的构建信息。

'正确'代码版本来自vars文件,名为desired_build_id

如何验证我的version.properties是否提到此构建ID?某种子字符串搜索?

我尝试过以下方法:

--- 
- name: Validate deployment success
  hosts: app-nodes
  tasks:
    - name: Read version.properties file
      shell: cat /path/to/version.properties
      register: version_prop_content

    - fail: Wrong build ID found in version.properties
      when: desired_build_id not in version_prop_content.stdout 

然而,这会产生错误:error while evaluating conditional: esired_build_id not in version_prop_content.stdout

这是什么正确的语法?或者,有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

想出来了!

进行子字符串比较的方法是使用version_prop_content.stdout.find(desired_build_id) > 0,如果存在子字符串则为true

find命令返回子字符串的索引,如果不存在则返回-1。

我还将其更改为断言任务,使其看起来更漂亮(fail是一个丑陋的词;))。

- name: Check that desired version was deployed
  assert:
    that: 
      - version_prop_content.stdout.find(desired_build_id) > 0

答案 1 :(得分:2)

一个更简单的python表达式也可以:

- name: Read version.properties file
  shell: cat /path/to/version.properties
  register: version_prop_content

- debug: msg="desired build installed"
  when: "'{{desired_build_id}}' in '{{version_prop_content.stdout}}'"

或者我一直建议,尽量避免使用ansible

- name: verify version
  shell: grep '{{desired_build_id}}' /path/to/version.properties
相关问题