1

I have a json file (server.json) with the content like this:

   servers_groupA: [{server_name: server1abc.net, start_file: w.bat, stop_file: d.bat},
           
          {server_name: server2.abc.net, start_file: w.bat, stop_file: d.bat}
          ]
    servers_groupB: [{server_name: server3.abc.net, start_file: e.bat, stop_file: f.bat},
           
          {server_name: server4.abc.net, start_file: e.bat, stop_file: f.bat }
          ]

I have to assign this servers to a group dynamically with the below code:

           hosts: localhost
           gather_facts: false
           ignore_errors: yes
           vars:
             server_vaar: "servers_groupA"
             #server_vaar: {{ server_group }}
       
       
    tasks:
          
          - name: Importing json file
            include_vars: 
              file: server.json
            
              
          - name: Adding host dynamically to inventory
            add_host:
              hostname: "{{ item.server_name }}"
              groups: testing_servers_group
              ansible_connection: winrm
              ansible_port: 5985
              ansible_winrm_transport: ntlm
              ansible_winrm_scheme: http  
              ansible_winrm_server_cert_validation: ignore
              ansible_winrm_operation_timeout_sec: 60
              ansible_winrm_read_timeout_sec: 70           
            with_items: "{{ server_vaar }}"

So value for server_vaar mentioned in vars will be passed to the script as extra variable from Splunk or by manually when the ansible script runs.

This server_vaar value can be servers_groupA, servers_groupB, servers_groupC, servers_groupD. We need to pass this name to with_items in "Adding host dynamically to inventory" TASK. So that it will go that array in json file and pass the server_name from that list to inventory and create a group "testing_servers_group" as Inventory group.

So I passed in with_items: "{{ server_vaar}}" which should be taken as with_items: "{{ servers_groupA }}"

But it throwed error as "undefined variable" for that server_vaar. I couldnot find a solution to pass this groupname to the with items. Can anyone give me some idea on this issue I am facing.

saffron
  • 143
  • 1
  • 3
  • 12

1 Answers1

1

Use lookup plugin vars. For example

loop: "{{ lookup('vars', server_vaar) }}"
Vladimir Botka
  • 5,138
  • 8
  • 20