184

I'm setting up an Ansible playbook to set up a couple servers. There are a couple of tasks that I only want to run if the current host is my local dev host, named "local" in my hosts file. How can I do this? I can't find it anywhere in the documentation.

I've tried this when statement, but it fails because ansible_hostname resolves to the host name generated when the machine is created, not the one you define in your hosts file.

- name: Install this only for local dev machine
  pip: 
    name: pyramid
  when: ansible_hostname == "local"
Kevin C
  • 4,851
  • 8
  • 30
  • 64
Tanner Semerad
  • 12,472
  • 12
  • 40
  • 49

3 Answers3

301

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: 
    name: pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

Kevin C
  • 4,851
  • 8
  • 30
  • 64
Tanner Semerad
  • 12,472
  • 12
  • 40
  • 49
  • 2
    Variable currently is documented at: https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html – vivimice May 17 '22 at 02:21
4

You can limit the scope of a playbook by changing the hosts header in its plays without relying on your special host label ‘local’ in your inventory. Localhost does not need a special line in inventories.

- name: run on all except local
  hosts: all:!local
bbaassssiiee
  • 6,013
  • 2
  • 42
  • 55
0

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost
bbaassssiiee
  • 6,013
  • 2
  • 42
  • 55