Ansible检查清单主机名是否在列表中 [英] Ansible check if inventory_hostname is in list

查看:72
本文介绍了Ansible检查清单主机名是否在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查 inventory_hostname 是否在导入变量的列表中.

I am trying to check if inventory_hostname is in a list into an imported variable.

vars/users.yml file:
---
users:

  - username: user1
    comment: "User 1"
    group: admin
    password: "sha password"
    keys:
      active:
        - "ssh-rsa etc"
    admin: yes

  - username: user2
    comment: "User 2"
    group: users
    groups: deployer
    keys:
      active:
        - "ssh-rsa etc"
    hosts:
      user:
        - host1
        - host2
      deployer:
        - host3

仅当 inventory_hostname 进入任何主机列表(用户,部署者,其他...)时,我才想执行任务.

I want to execute a task only if inventory_hostname is into any of hosts lists (user, deployer, others ...).

我尝试过:

- name: Create users
  user:
    name: "{{ item.username }}"
    comment: "{{ item.comment | default('User {{item.username}}') }}"
    password: "{{ item.password | default('!') }}"
    state: "{{ item.state | default('present') }}"
    shell: "{{ item.shell | default('/bin/bash') }}"
    group: "{{ item.group | default('users') }}"
  with_items: '{{ users }}'
  when: item.username is defined and ((item.admin is defined and item.admin == True) or (item.hosts is defined and item.hosts.user is defined and inventory_hostname in item.hosts.user)

它适用于 user1 (已启用管理员),但不适用于 user2 (如果此播放是在 host1 中执行的,user2的hosts.user列表).

It works for user1 (which have admin enabled) but not for user2 (if this play is executed on host1 which is included into user2's hosts.user list).

推荐答案

好..我尝试了您的代码段,并且对两个用户都适用.唯一可能导致失败的原因是 item.host.user 中的主机名与 inventory_hostname 不匹配.您可以在执行此任务之前尝试调试 inventory_hostname ,以查看ansible读取的库存主机名以及是否在 item.host.user 列表中正确指定了它们.

Well .. I tried your code snippet and it works well for both users. Only thing which can make it fail is that hostnames in item.host.user are not matching the inventory_hostname. You can try to debug the inventory_hostname before this task to see what are the inventory hostnames read by ansible and whether you have specified them correctly in item.host.user list.

- debug: var=inventory_hostname

这篇关于Ansible检查清单主机名是否在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆