simbo1905
simbo1905

Reputation: 6872

how to check the current host appears in a variable list within ansible?

I want to run a microservice role multiple times against hosts to install multiple services. I would also like to use ansible to move services around. This implies that I run against all my hosts and do some logic to check whether the service is installed and whether it should be installed.

I am finding it easy to check whether the service is or isn't installed. What I am doing to check whether the service should be installed is clunky. In my playbook I defined a list of hosts that should have the role installed:

roles:
    - {
      role: "ansible-role-springboot",
      sb_app_name: "microservices-registration",
      sb_app_group_id: "org.springframework.samples.service.service",
      sb_app_artifact_id: "microservices-demo",
      sb_app_version: "2.0.0.RELEASE",
      sb_hosts: [
        "my-test-vm"
      ]
    }

Then I am wanting to test a fact "is the current host in the list?". With my particular test kitchen ansible setup the inventory_hostname is always coming out as localhost even though the vm has the correct hostname. So I am wanting to test the output of the command hostname -f is in var list sb_hosts. This is what I have come up with:

- name: Transfer the script
  copy: src=host_test.sh dest=/home/sbuser mode=0777

- name: Resolve hostname
  command: "/home/sbuser/host_test.sh {{ sb_hosts }}"
  register: hostname_output

- set_fact: 
    hostname_listed="{{ 'HOSTNAME_LISTED' in hostname_output.stdout}}"

Where host_test.sh is:

#!/bin/sh
HOSTNAME=$(hostname -f)
VARS=$1
if echo $VARS | grep $HOSTNAME; then
    echo HOSTNAME_LISTED
else
    echo HOSTNAME_NOT_LISTED
fi

Copying a shell script to do something so basic feels very clunky. Is there a cleaner way to check "is is variable scalar within this variable list"?

Upvotes: 0

Views: 1908

Answers (2)

simbo1905
simbo1905

Reputation: 6872

In finally went with:

ansible_hostname in sb_hosts

Upvotes: 0

mdaniel
mdaniel

Reputation: 33231

If {{ inventory_hostname in sb_hosts }} is false, then perhaps {{ ansible_hostname in sb_hosts }} or {{ ansible_nodename ...etc... }}, or the catch-all {{ ([inventory_hostname, ansible_hostname, etcetc] | intersect(sb_hosts) | length) != 0 }}

You can obtain a full list of the names that ansible knows about via the setup command, or by dumping - debug: var=hostvars to see what fun toys are hiding in there.

If there is a catalog of the available hostvars populated by setup, then I don't know off-hand where to find it.

Upvotes: 1

Related Questions