Search code examples
moduleansiblehost

How to add a host that is a variable before executing a module in ansible?


This is the task I want to execute

- hosts: variable-vm
  become: yes
  tasks:
   - name: Transfer file from local to remote
     copy:
       src: /tmp/file
       dest: /home/ansible/

Now before the user executes my playbook I want him to enter

--extra-vars "server=variable-vm"

In other tasks this was defined at the beginning of the yml file like this:

- hosts: webservers
  vars:
    my_server: "{{ server }}"
  become: yes
  tasks:

and when I needed to I would deligate the task to that variable vm with

 delegate_to: '{{ my_server }}'

Keep in mind that I have defined the variable-vm inside the inventory under "webservers"

Essentially my machine is connected to dozens of servers with ssh keys and the servers are defined under /etc/hosts. All I want from the user is to enter the name of the server that is defined in /etc/hosts and use that variable as an input for "hosts:" before the copy task.

As far as I can see there is no other way to specify the remote machine I want to copy the file to.


Solution

  • @CzipO2, You can send the host using extra_vars to the ansible-playbook command as shown below,

    ansible-playbook -i hosts main.yml -e new_host=192.168.10.10
    

    And can delegate the task to this host.

    According to my knowledge, it is not possible to take host in a variable and then run the tasks on it, you can always delegate the task to the host specified using extra_vars.