How do I use Ansible command with items?

I want to set up my Ansible game to copy some lines from my file /etc/hosts

to a temporary file. It should be easy to do:

---
hosts: 127.0.0.1
gather_facts: False
tasks:
  - command: grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup
    with_items:
      - web
      - database

      

I would have thought it would work, but I am getting the error:

TypeError: string pointers must be integer, not str

I know Ansible is picky about unquoted parentheses, so I put double quotes throughout the command line, but I still get the error.

- command: "grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup"

      

+3


source to share


1 answer


I have no idea why you are getting the error you are claiming (it might be OS related if your system returns a strange Ansible error message).

Of course, you cannot use file redirection with a module command

. You need to use a module instead shell

, so replace your action with:

- shell: grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup

      



Also, your task has no problem with with_items

. For the game, no -

.

The following code works:

---
- hosts: 127.0.0.1
  gather_facts: False
  tasks:
    - shell: grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup
      with_items:
        - web
        - database

      

+4


source







All Articles