Ansible - read inventory hosts and variables to group_vars/all file

前端 未结 7 1842
醉酒成梦
醉酒成梦 2020-12-23 11:47

I have a dummy doubt that keeps me stuck for a long time. I have a very banal inventory file with hosts and variables:

[lb]
10.112.84.122

[tomcat]
10.112.84         


        
7条回答
  •  悲&欢浪女
    2020-12-23 12:31

    Yes the example by nixlike works very well.

    Inventory:

    [docker-host]
    myhost1 user=barbara
    myhost2 user=heather
    

    playbook:

    ---
    
    - hosts: localhost
      connection: local         
    
         tasks:    
            - name: loop debug inventory hostnames
              debug: 
                msg: "the docker host is {{ item }}"
              with_inventory_hostnames: docker-host
            - name: loop debug items
              debug: 
                msg: "the docker host is {{ hostvars[item]['user'] }}"
              with_items: "{{ groups['docker-host'] }}"
    

    output:

    ansible-playbook ansible/tests/vars-test-local.yml

    PLAY [localhost]


    TASK [setup] ******************************************************************* ok: [localhost]

    TASK [loop debug inventory hostnames] ****************************************** ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is myhost2" } ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is myhost1" }

    TASK [loop debug items] ******************************************************** ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is barbara" } ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is heather" }

    PLAY RECAP ********************************************************************* localhost : ok=3 changed=0 unreachable=0
    failed=0

    thanks!

提交回复
热议问题