如何检查Ansible命令输出中是否存在字符串列表?

Tan*_*rad 22 grep ansible

我想在shell命令不返回预期输出的情况下运行Ansible操作.ogr2ogr --formats漂亮打印兼容文件格式列表.我想grep格式输出,如果我的预期文件格式不在输出中,我想运行命令来安装这些组件.有谁知道如何做到这一点?

- name: check if proper ogr formats set up
  command: ogr2ogr --formats | grep $item
  with_items:
    - PostgreSQL
    - FileGDB
    - Spatialite
  register: ogr_check

# If grep from ogr_check didn't find a certain format from with_items, run this
- name: install proper ogr formats
  action: DO STUFF
  when: Not sure what to do here
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 28

首先,请确保您使用的是Ansible 1.3或更高版本.Ansible仍然可以从我所看到的变化很快,并且许多令人敬畏的功能和错误修复是至关重要的.

至于检查,您可以尝试这样的事情,利用grep退出代码:

- name: check if proper ogr formats set up
  shell: ogr2ogr --formats | grep $item
  with_items:
    - PostgreSQL
    - FileGDB
    - Spatialite
  register: ogr_check
  # grep will exit with 1 when no results found. 
  # This causes the task not to halt play.
  ignore_errors: true

- name: install proper ogr formats
  action: DO STUFF
  when: ogr_check|failed
Run Code Online (Sandbox Code Playgroud)

还有一些其他有用的寄存器变量,即item.stdout_lines.如果您想详细了解变量中注册的内容,请尝试以下任务:

- debug: msg={{ogr_check}}
Run Code Online (Sandbox Code Playgroud)

然后通过双重详细模式运行任务ansible-playbook my-playbook.yml -vv.它会吐出很多有用的字典值.

  • "ogr_check|failed" 过滤器已被弃用。改用:“ogr_check 失败”。 (2认同)

小智 8

我的解决方案

- name: "Get Ruby version"
command: "/home/deploy_user/.rbenv/shims/ruby -v"
changed_when: true
register: ruby_installed_version
ignore_errors: true

- name: "Installing Ruby 2.2.4"
command: '/home/deploy_user/.rbenv/libexec/rbenv install -v {{ruby_version}}'
become: yes
become_user: deployer
when: " ( ruby_installed_version | failed ) or ('{{ruby_version}}' not in ruby_installed_version.stdout) "
Run Code Online (Sandbox Code Playgroud)