使用with_sequence循环时出现错误

时间:2019-01-03 12:48:54

标签: ansible

我正在尝试使用ansible循环代码,

  - file:
  state: touch
  path: /tmp/{{ item }}
with_sequence: start=0 end={{ find_result.examined }} 

this works the directorys are created

但是如果我使用相同的循环创建用户,则会出现错误

 - name: User Creation
user:
  name: "{{ find_result.files[item].path | regex_replace('/root/00staging/sshkeys/') | regex_replace('_id_rsa.pub')}}"
  comment: nameduser
  password: "{{ 'Start123' | password_hash('sha512') }}"
  update_password: on_create
  createhome: true
  group: wheel
register: users_added
with_sequence: start=0 end={{ find_result.examined }}

错误:

{"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute u'0'\n\n

它在我使用循环with_items时有效,但这不够动态

变量不为空,它将被以下代码填充:

  - name: finding files
find:
  paths:            "/root/00staging/sshkeys"
  file_type:        "file"
register: find_result

更新:

我在使用简单序列号时遇到了相同的错误,[项目]未填充,但{{item}}正确填充

find_result.files [item] .path

with_sequence:start = 0 end = 1

1 个答案:

答案 0 :(得分:0)

您看到的错误:

'list object' has no attribute u'0'

建议find_result.files键的值是一个空列表。在循环的第一次迭代中,您尝试访问find_result.files[0],但是如果该列表为空,则不存在元素0。您可以通过以下示例生成相同的错误:

---
- hosts: localhost
  gather_facts: false
  vars:
    empty_list: []
  tasks:
    - debug:
        msg: "item {{ item }} is {{ empty_list[item] }}"
      with_sequence: start=0 end=1

您应该检查find_result变量的内容(例如使用debug任务),以确认该变量包含您认为应包含的内容。