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

查看:37
本文介绍了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天全站免登陆