3

how to iterate on all specified hosts

 2 years ago
source link: https://www.codesd.com/item/how-to-iterate-on-all-specified-hosts.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

how to iterate on all specified hosts

advertisements

I have a playbook that is supposed to create a config file for all specified hosts, on my monitoring_sever.

- hosts: all
  gather_facts: True

  hosts: monitoring_server
  tasks:
  - command: touch {{ hostvars[item]['ansible_fqdn'] }}
    with_items: "{{ groups['all'] }}"

I execute the playbook with ansible-playbook main.yml -l "new_client, new_client2, monitoring_server"

The Resulting files on the monitoring server should look like the following:
client1.conf client2.conf

But I get an error about missing quotes, I've tried all sorts of syntax changes but I can't seem to find the problem.


Updated:

- hosts: all
  gather_facts: True

  tasks:
    - file:
        path: "{{ hostvars[item]['ansible_fqdn'] }}"
        state: touch
      delegate_to: host_name # Delegate task to specific host
      with_items: "{{ groups['all'] }}"

You have typos in your original playbook.

  1. with:items should be with_items
  2. items should be item

Usage of delegate_to: http://docs.ansible.com/ansible/playbooks_delegation.html#delegation


As long as you are targeting all hosts, you don't have to make a loop as Ansible executes tasks on all targeted hosts unless excluded by condition.

On the other hand, I would suggest using file module instead of command to touch the file.

- hosts: all
  tasks:
    - name: Touch a file
      file:
        path: "{{ ansible_fqdn }}"
        state: touch

PS. I assumed ansible_fqdn is a host var you defined for each host.

Tags ansible

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK