Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run local command via ansible-playbook

Tags:

ansible

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

Eg: I wanted to run a command "knife node create {{ hostname }}" in my local machine(laptop). The playbook is:

- 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:

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

Ofcourse, it wont work as the inventory has 'qa-hosts' and the play is for '127.0.0.1', as I wanted the play to run from my local machine.

Would anyone help me with an idea how to get it done. Basically, I want get the variable 'hostname' and pass it to above play block.

like image 789
Nandan A Avatar asked May 16 '17 14:05

Nandan A


1 Answers

I like delegate_to. Here's an example that, on localhost, runs getent hosts 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
like image 103
Jack Avatar answered Sep 18 '22 06:09

Jack