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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With