0

I want to take out the ip value of all servers that match the when condition.

My ansible-playbook is as follows:

- name: Get all the servers with docker installed
  shell: docker -v
  failed_when: False
  register: docker_exists

- name: Get the server where docker is installed
  shell: echo "{{inventory_hostname}}"
  register: docker_ip
  when: "'Docker version 18.09.6' in docker_exists.stdout"

Tested, the docker_ip variable is not a global variable, but only on a machine that satisfies the condition of "Docker version 18.09.6' in docker_exists.stdout", on a machine that does not satisfy this condition. Direct error, suggesting The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout', how can I use the docker_ip variable globally??

~~Now how do I get all the server ips with docker installed through docker_exists, and the server without docker installed? Must obtain the ip value that satisfies the condition~~

~~Or is there any other way to get all the ips that satisfy the when condition?~~

cydia
  • 103
  • 12

1 Answers1

0

You have a lot of questions in your question, but here we go:

how can I use the docker_ip variable globally??

There is no such thing as "globally" -- all variables in ansible are "host" variables

Now how do I get all the server ips with docker installed through docker_exists, and the server without docker installed?

- name: declare discovered docker hosts
  set_fact:
    hosts_with_docker: >-
      {%- set results = [] -%}
      {%- for hn in groups["all"] -%}
      {%- if "Docker version" in hostvars[hn].get("docker_exists", {"stdout": ""}).stdout -%}
      {%- set _ = results.append(hn) -%}
      {%- endif -%}
      {%- endfor -%}
      {{ results }}

If you quite literally mean the IP, and not the inventory_hostname, the change results.append(hn) to results.append(hostvars[hn].ansible_default_ipv4.address)

Or is there any other way to get all the ips that satisfy the when condition?

In general, no, because every set_fact (which register: is just a convenient shortcut) is per host, so looping over all hosts is the only way to "broadcast" that information in a playbook

mdaniel
  • 31,240
  • 5
  • 55
  • 58