Ansible - Define Inventory at run time

后端 未结 2 1936
灰色年华
灰色年华 2021-02-10 09:06

I am liitle new to ansible so bear with me if my questions are a bit basic.

Scenario:

I have a few group of Remote hosts such as [EPCs] [Clients] and [Testers] I

2条回答
  •  庸人自扰
    2021-02-10 09:17

    You should use vars_prompt for getting information from user, add_host for updating hosts dynamically and with_sequence for loops:

    $ cat aaa.yml
    ---
    - hosts: localhost
      gather_facts: False
      vars_prompt:
        - name: range
          prompt: Enter range of EPCs (e.g. 1..5)
          private: False
          default: "1"
      pre_tasks:
        - name: Set node id variables
          set_fact:
            start: "{{ range.split('..')[0] }}"
            stop: "{{ range.split('..')[-1] }}"
        - name: "Add hosts:"
          add_host: name="host_{{item}}" groups=just_created
          with_sequence: "start={{start}} end={{stop}} "
    
    - hosts: just_created
      gather_facts: False
      tasks:
        - name: echo sequence
          shell: echo "cmd"
    

    The output will be:

    $ ansible-playbook aaa.yml -i 'localhost,'

    Enter range of EPCs (e.g. 1..5) [1]: 0..1
    
    PLAY [localhost] **************************************************************
    
    TASK: [Set node id variables] *************************************************
    ok: [localhost]
    
    TASK: [Add hosts:] ************************************************************
    ok: [localhost] => (item=0)
    ok: [localhost] => (item=1)
    
    PLAY [just_created] ***********************************************************
    
    TASK: [echo sequence] *********************************************************
    fatal: [host_0] => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue
    fatal: [host_1] => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue
    
    FATAL: all hosts have already failed -- aborting
    
    PLAY RECAP ********************************************************************
               to retry, use: --limit @/Users/gli/aaa.retry
    
    host_0                     : ok=0    changed=0    unreachable=1    failed=0
    host_1                     : ok=0    changed=0    unreachable=1    failed=0
    localhost                  : ok=2    changed=0    unreachable=0    failed=0
    

    Here, it failed as host_0 and host_1 are unreachable, for you it'll work fine.

    btw, I used more powerful concept "range of nodes". If you don't need it, it is quite simple to have "start=0" and ask only for "stop" value in the prompt.

提交回复
热议问题