Ansible: how to construct a variable from another variable and then fetch it's value

前端 未结 10 498
我寻月下人不归
我寻月下人不归 2020-12-02 22:50

Here is my problem I need to use one variable \'target_host\' and then append \'_host\' to it\'s value to get another variable name whose value I need. If you look at my pl

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 23:08

    You can use "hostvars" to pass the variable, host facts can be loaded from group vars or host vars

    yml

    ---
    - name: "Play to for dynamic groups"
      hosts: x0
      vars:
        - target_host: smtp
      tasks:
        - set_fact: smtp_host="smtp.max.com"
        - set_fact: host_var_name={{target_host}}_host
        - set_fact: dym_target_host={{hostvars[inventory_hostname][host_var_name]}}
    
        - name: testing
          debug: msg={{ target_host }}
        - name: testing
          debug: msg={{ smtp_host }}
        - name: testing
          debug: msg={{ target_host }}_host
        - name: testing
          debug: msg={{ dym_target_host }}
    

    output:

    PLAY [Play to for dynamic groups] *********************************************
    
    GATHERING FACTS ***************************************************************
    ok: [x0]
    
    TASK: [set_fact smtp_host="smtp.max.com"] *************************************
    ok: [x0]
    
    TASK: [set_fact host_var_name=smtp_host] **************************************
    ok: [x0]
    
    TASK: [set_fact dym_target_host={{hostvars[inventory_hostname][host_var_name]}}] ***
    ok: [x0]
    
    TASK: [testing] ***************************************************************
    ok: [x0] => {
        "msg": "smtp"
    }
    
    TASK: [testing] ***************************************************************
    ok: [x0] => {
        "msg": "smtp.max.com"
    }
    
    TASK: [testing] ***************************************************************
    ok: [x0] => {
        "msg": "smtp_host"
    }
    
    TASK: [testing] ***************************************************************
    ok: [x0] => {
        "msg": "smtp.max.com"
    }
    
    PLAY RECAP ********************************************************************
    x0                         : ok=8    changed=0    unreachable=0    failed=0
    

提交回复
热议问题