burg
burg

Reputation: 1

Ansible subtasks with dynamic hosts

I have a dictionary with hostnames. To every hostname I would like to connect via SSH and to some tasks.

I tried something like this, but this does not work. Any tips and tricks how to achieve this.

main.yml

---
- hosts: all
  connection: network_cli
  vars:
    - input: "{{ lookup('file','temp/yoda-xxx-xx.json') | from_json }}"
    - ansible_network_os: nokia.sros.classic
    - ansible_ssh_user: user
    - ansible_password: password
  tasks:
    - name: Configure Main
      - include_tasks: worker.yml
        with_items: "{{ input.delta_config }}"

worker.yml

---
- hosts: "{{ item.device }}"
  gather_facts: No
  connection: network_cli

  tasks:
    - name: Configure 
      community.network.sros_config:
        src: "temp/{{ item.device }}"
        save: yes
        match: line

JSON Input

{
   "device":"yoda-xxx-xx",
   "config_file":"C:\yoda-xxx-xx.cfg",
   "delta_config":[
      {
         "device":"yoda-yy-01",
         "config_file":"temp/yoda-xxx-xx_delta_for_yoda-yy-01.txt"
      },
      {
         "device":"yoda-yy-02",
         "config_file":"temp/yoda-xxx-xx_delta_for_yoda-yy-02.txt"
      }
   ]
}

Upvotes: 0

Views: 387

Answers (1)

George Shuklin
George Shuklin

Reputation: 7917

You can't include_tasks a playbook. include_tasks is used to include a tasklist (a list of tasks without hosts: ... and tasks: statements).

If you want to use dynamic hosts, use add_host module.

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/add_host_module.html

Alternatively, you may write a proper inventory snippet into a directory with a current inventory (you need to turn your inventory into a directory for that) and to do meta: refresh_inventory call to see new hosts.

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/meta_module.html

Upvotes: 0

Related Questions