Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Ansible command with items?

Tags:

ansible

I want to configure my Ansible playbook to copy certain lines out of my /etc/hosts file into a temporary file. This 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'd think this would work but I'm getting an error:

TypeError: string indicies must be integers, not str

I know Ansible is picky about unquoted braces so I put double quotes around the entire command line but I still get the error.

- command: "grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup"
like image 670
Jim Avatar asked Mar 22 '17 19:03

Jim


1 Answers

I have no idea why you get the error you claim you get (maybe it's an OS-related thing if your system returns a strange error message to Ansible).

One thing for sure is you cannot use file redirection with command module. Instead you need to use shell module, so replace your action with:

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

Other than that, there is no problem with with_items in your task. There is no - for the play though.

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
like image 96
techraf Avatar answered Sep 20 '22 03:09

techraf