执行ansible playbook时,属性不存在错误

时间:2017-08-04 09:49:57

标签: ansible

我正在尝试执行现有的ansible playbook,我收到了这个错误:

fatal: [default]: FAILED! => {"failed": true, "msg": "ERROR! 'unicode object' has no attribute 'regexp'"}

执行ansible playbook的这一部分时:

- name: "Add access to pg_hba.conf for DB users"
  become: yes
  become_user: postgres
  lineinfile: dest="{{ PATH_PG_HBA }}" regexp="{{ item.regexp }}" line="{{ item.line }}" state=present create=yes
  with_items: "{{ DATABASE_ACL }}"
  notify: restart postgresql

显然,正则表达式中不存在正则表达式。但是由于我在ansible中的经验有限,我想知道这是否是与lineinfile参数或此ansible yaml文件特定内容相关的一般错误。

{{DATABASE_ACL}}变量在group_vars文件夹中声明为:

DATABASE_ACL:
 - "local {{ DB_NAME }} {{ DB_USER }} md5"
 - "host {{ DB_NAME }} {{ DB_USER }} 127.0.0.1/32 md5"
 - "host {{ DB_NAME }} {{ DB_USER }} 10.0.2.2/32 md5"

在同一文件夹中声明了DB_NAME和DB_USER(字符串)。

1 个答案:

答案 0 :(得分:1)

DATABASE_ACL from your group vars is a list of strings, and item in loop is a unicode string. Obviously, as you said, this error tells you exactly this - unicode string doesn't have attribute regexp. This exact error can be reproduced in ipython, like:

In [1]: a = unicode("some string")

In [2]: a.regexp
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-26893273be72> in <module>()
----> 1 a.regexp

AttributeError: 'unicode' object has no attribute 'regexp'

If you want to use your current task, you have to change data structure of DATABASE_ACL to a list of dicts in a yaml, for example like

DATABASE_ACL:
 - line: "local {{ DB_NAME }} {{ DB_USER }} md5"
   regexp: "local"
 - line: "host {{ DB_NAME }} {{ DB_USER }} 127.0.0.1/32 md5"
   regexp: "host .* 127"
 - line: "host {{ DB_NAME }} {{ DB_USER }} 10.0.2.2/32 md5"
   regexp: "host .* 10.0.2.2"

The resulting item will be dict, structured as {line: "your line", regexp: "your regexp"}, which will work correctly in your case.