How to use Ansible's with_item with a variable

2019-01-01 04:30发布

I'm trying to transform some fields of the items of a list in an Ansible Playbook. Here is the simplest reproduction path, skipping the transformation. The result should be identical to the users variable.

---
# Run with:
# ansible-playbook -i "localhost," loop3.yml

- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    users:
      - name: paul
        uid: 1
      - name: pete
        uid: 2
  tasks:
    - set_fact:
      args:
        useritem:
          name: '{{ item.name }}'
          uid:  '{{ item.uid }}'
      with_items:
        - users
      register: sf_result

    - debug: var=sf_result

    - set_fact:
        userslist: "{{ sf_result.results | map(attribute='ansible_facts.useritem') | list }}"

    - debug: var=userslist

I get this error:

TASK [set_fact useritem={u'name': u'{{ item.name }}', u'uid': u'{{ item.uid }}'}] ***
fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! 'unicode object' has no attribute 'name'"}

There are several examples very close to what I needbut I could find no working example using set_fact along with with_items and items as a map.

I've tried Ansible 1.9.2, 1.9.4, and 2.0.0-0.6.rc1 with different error messages but no more success. Ansible 2 should allow skipping the second call to set_fact but the error happens before getting there.

标签: ansible
1条回答
与君花间醉酒
2楼-- · 2019-01-01 05:01

I thought I did read somewhere that with_items accepts a bare variable name, but it's not the case.

The program runs as expected using:

with_items: "{{ users }}"
查看更多
登录 后发表回答