Forum Discussion

BigD_300005's avatar
BigD_300005
Icon for Cirrostratus rankCirrostratus
Feb 09, 2018

Ansible Dynamic node tasks

Is there a way in Ansible to get the node task to spin off multiple times without having to manually create 3 node tasks? I'd like to just have one playbook instead of multiple depending on how many nodes you need.

server_count = 3
i = 1
while i <= server_count:
    node task stuff here
    i = i + 1


  - name: Create server [i]
    bigip_node:
        password: "{{ bigip_password }}"
        server: "{{ ansible_host }}"
        user: "{{ bigip_username }}"
        partition: "{{ partition }}"
        host: "{{ server[i]_ip }}"
        name: "{{ server[i]_name }}"
        validate_certs: "false"
        state: "present"
    delegate_to: localhost
  • Looping over Parallel Sets of Data

     

    Suppose you have the following variable data was loaded in via somewhere:

     

    alpha: [ 'a', 'b', 'c', 'd' ] numbers: [ 1, 2, 3, 4 ] And you want the set of ‘(a, 1)’ and ‘(b, 2)’ and so on. Use ‘with_together’ to get this:

     

    tasks: - debug: msg="{{ item.0 }} and {{ item.1 }}" with_together: - "{{alpha}}" - "{{numbers}}"

     

    We can use the above loop to fulfill our requirement where to create/use multiple nodes in respective of LB or where to use multiple items.

     

    Reference - http://ansible-docs.readthedocs.io/zh/stable-2.0/rst/playbooks_loops.html

     

    • prt1969_120570's avatar
      prt1969_120570
      Icon for Nimbostratus rankNimbostratus

      Does anyone have a simple example to test with or use as a template?

       

  • My playbook for this case is:

     tasks:
    - name: ADD NODES 
      bigip_node:
        state: present
        partition: "{{ f5_partition }}"
        server: "{{ f5_server }}"
        user: "{{ f5_user }}"
        password: "{{ f5_pass }}"
        name: "{{ item.f5_node_name }}"
        host: "{{ item.f5_node_host }}"
        validate_certs: no
      delegate_to: localhost
      with_items: "{{ f5_nodes_list }}" 
    

    Example for node list:

    f5_server: f5host.local
    f5_partition: partition1
    f5_user: user1
    f5_pass: vault
    f5_nodes_list:
      - f5_node_name: node-1
        f5_node_host: 1.1.1.3 
      - f5_node_name: node-2
        f5_node_host: 1.1.1.4