Ansible check if inventory_hostname is in list

拥有回忆 提交于 2019-12-24 22:08:39

问题


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

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

I tried this:

- 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)

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).


回答1:


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


来源:https://stackoverflow.com/questions/53237393/ansible-check-if-inventory-hostname-is-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!