Ansible - 使用用户输入选择变量

时间:2016-12-28 21:17:55

标签: ansible ansible-playbook

我想根据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

运行剧本时的输出:

[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   

我想知道如何或最好的方法将位置的读入用户输入与变量部分顶部定义的位置的实际值(IP地址)相关联。可能是评估还是其他什么?

1 个答案:

答案 0 :(得分:2)

您的任务正在等待loc2,因此消息Timeout when waiting for loc2:9999

改为使用host={{ vars[location] }}

比较以下任务的输出:

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

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

结果(缩写):

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"
}