首页 > 解决方案 > 即使使用正确的语法,Ansible 任务也会失败

问题描述

我正在学习 ansible,并且我已经为 LDAP 验证编写了一个任务。但是,当我运行剧本时,即使验证正确,任务也会失败。

下面是检查 LDAP 密码最大年龄的 ansible 任务

- name: LDAP Validation
      shell: /usr/bin/ldapsearch -w admin  -H ldap://localhost:10389 -x -D "cn=manager,dc=apache,dc=com" -b "cn=default,ou=pwpolicies,dc=apache,dc=com" | grep 'pwdMaxAge'
      register: output


- name: LDAP password age check 
  fail:
    msg: "Password MaxAge not set to 0"
  when: output.stdout != "pwdMaxAge: 0"

下面是更新任务后 ansible 抛出的新语法错误。

ERROR! Syntax Error while loading YAML.
  mapping values are not allowed here

The error appears to have been in '/etc/ansible/server/roles/LDAP/tasks/ldap.yml': line 40, column 36, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

    msg: "Password MaxAge not set to 0"
  when: output.stdout != "pwdMaxAge: 0"
                                   ^ here

标签: ansibleansible-2.xansible-inventoryansible-factsansible-template

解决方案


变量output是字典;将它与字符串进行比较是没有意义的:比较永远不会相等。查看文档以了解shell模块返回的值。

例如,您最终可能会stdout像这样检查属性:

- name: LDAP password age check 
  fail:
    msg: "Password MaxAge not set to 0"
  when: 'output.stdout != "pwdMaxAge: 0"'

正如@PatrickForget 建议的那样,您可以使用debug任务来检查您的注册变量:

- name: show output variable
  debug:
    var: output

推荐阅读