Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - Using user input to chose a variable

Tags:

ansible

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?

like image 916
nickyt4free Avatar asked Oct 27 '25 09:10

nickyt4free


1 Answers

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"
}
like image 193
techraf Avatar answered Oct 29 '25 07:10

techraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!