How to run a local command via a download file

I am trying to run some local command by iterating through the inventory file and taking each hostname as an argument to the local command.

For example: I wanted to run the command "knife node create {{hostname}}" on my local machine (laptop). Playlist:

- name: Prep node
  hosts: 127.0.0.1
  connection: local
  gather_facts: no
  tasks:
  - name: node create
    command: "knife node create {{ hostname | quote }}"

      

and my inventory file looks like this:

[qa-hosts]
10.10.10.11 hostname=example-server-1

      

Of course this will not work since the inventory has "qa-hosts" and the game is for "127.0.0.1", since I wanted the game to run from my local machine.

Can anyone help me with an idea how to do this. Basically, I want to get the "hostname" variable and pass it to the playhead above.

+3


source to share


2 answers


You can access the hostname using the following game as the inventory information is available as hosts.



- hosts: 127.0.0.1   
  connection: local
  gather_facts: no

  tasks:
    - debug: var=hostvars

    - name: node create
      command: "knife node create {{ hostvars[item]['hostname'] }}"
      with_items:
        - "{{ groups['qa-hosts'] }}"

      

+2


source


I like delegate_to . Here's an example that runs getent hosts on localhost for each host:



---
- hosts: all
  connection: ssh
  gather_facts: true
  tasks:
  - name: Lookup ansible_hostname in getent database
    command: getent hosts {{ ansible_hostname }}
    delegate_to: localhost
    register: result

  - name: Show results
    debug:
      var: result.stdout
    delegate_to: localhost

      

+1


source







All Articles