首页 > 解决方案 > 如何让 Ansible 在本地运行以主机为参数的命令

问题描述

我使用 ansible playbook 在多个主机上安装了服务器。主机在清单文件中定义:

[services]
host_ip1
host_ip1
...

现在我需要使用命令测试每个主机是否正常工作:

service-cli -h <host_ip1> -p 6380 ping
...

我如何使用 ansible 编写它?可以肯定 ansible 会在本地而不是远程运行命令,那么如何将 host_ipX 传递给 ansible?

标签: ansible

解决方案


我知道如何使用delegate_to: 127.0.0.1,我不知道如何使用with_items获取库存文件的ip,我应该设置什么关键字?服务?

您的用例在示例中逐字记录extract

- debug:
    msg: service-cli -h {{ item }} -p 6380 ping
  with_items: '{{ groups["services"] | map("extract", hostvars, "ansible_host") }}'
  delegate_to: localhost
  # this is required if you want the task as part of a playbook
  # that contains "hosts: all"
  run_once: yes

或者,作为“run_once”的替代方案,您可以将其隔离为自己的游戏:

- hosts: localhost
  gather_facts: no
  tasks:
  - debug:
      msg: service-cli -h {{ item }} -p 6380 ping
    with_items: '{{ groups["services"] | map("extract", hostvars, "ansible_host") }}'

- hosts: all
  ... # and now back to normal life

推荐阅读