Ansible - Using user input to chose a variable

时间秒杀一切 提交于 2020-07-07 04:35:20

问题


I would like to select a specific variable based on user input in an Ansible playbook. Specifically, I would like to ask for user input on a location of a server, and then execute a specific action based on the input.

This is the current ansible playbook:

    - hosts: all
      remote_user: root
      gather_facts: True
      vars:
        loc1: "10.13.1.140"
        loc2: "10.13.1.141"
        loc3: "10.13.1.142"

    vars_prompt:
      - name: location
        prompt: "Location of server?  Input options: loc1/loc2/loc3"
        private: no

    tasks:
      - name: Test connectivity to user selected location
        wait_for: host={{ vars.location }} port=9999 delay=0 timeout=10 state=started

Output when running the playbook:

[root@ansmgtpr-labc01 cfengine]# ansible-playbook testpoo.yaml -i /tmp/test
SSH password: 
Location of server?  Input options: loc1/loc2/loc3: loc2

PLAY     ***************************************************************************

TASK [setup] *******************************************************************
ok: [hostname.domain.com]

TASK [Test connectivity to user selected location] *****************************
fatal: [hostname.domain.com]: FAILED! => {"changed": false, "elapsed": 10, "failed": true, "msg": "Timeout when waiting for loc2:9999"}

PLAY RECAP *********************************************************************
hostname.domain.com : ok=1    changed=0    unreachable=0    failed=1   

I would like to know how or the best way to link the read-in user input of the location with the actual value (IP address) of the location that is defined at the top in the variables section. Possibly eval or something else?


回答1:


Your task is waiting for loc2, hence the message Timeout when waiting for loc2:9999.

Use host={{ vars[location] }} instead.

Compare the output of the following tasks:

tasks:
  - name: Show the value user entered
    debug: var=vars.location

  - name: Use the entered value as an index
    debug: var=vars[location]

Result (abbreviated):

TASK [Show the value user entered] *********************************************
ok: [localhost] => {
    "vars.location": "loc2"
}

TASK [Use the entered value as an index] ***************************************
ok: [localhost] => {
    "vars[location]": "10.13.1.141"
}


来源:https://stackoverflow.com/questions/41369834/ansible-using-user-input-to-chose-a-variable

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