在hostvars中循环

时间:2018-11-21 00:42:08

标签: ansible f5

我想知道使用Ansible时是否可以在hostvars文件夹中执行循环?

这是我尝试过的但未成功完成的工作-还是做不到?

---

list_pool: 'list ltm pool {{ items }}'
with_items:
    - 'abc123'
    - 'def456'

之后,我会在剧本中使用“ list_pool”变量:

  - name: List pool
    bigip_command:
      server: "{{ some_server }}"
      user: "{{ some_user }}"
      password: "{{ some_password }}"
      commands: 
        - "{{ list_pool }}"
      validate_certs: no
    delegate_to: localhost

2 个答案:

答案 0 :(得分:0)

不确定当您说要遍历hostvars文件夹时的意思。 从您的任务可以理解为:“您需要对列表list ltm <pool-name>中的多个池执行big-ip命令list_pool

如果这就是您想要的,那应该可以:

- name: Set list_pool fact
  set_fact:
    list_pool: "{{ list_pool | default([]) + [item] }}"
  with_items:
     - 'abc123'
     - 'def456'

- name: List pool
  bigip_command:
    server: "{{ some_server }}"
    user: "{{ some_user }}"
    password: "{{ some_password }}"
    commands: 
      - "list ltm {{ item }}"
    validate_certs: no
  delegate_to: localhost
  with_items: "{{ list_pool }}"

答案 1 :(得分:0)

我通过以下解决方案来解决这个问题:

hostvars文件如下所示:

---    
pre_checks:
    checks:
        pool:
            - name: "pool_123"
            - name: "pool_456"
...

这出戏看起来像这样:

--output truncated---

      - name: Fetch device host_vars
        set_fact:
          device_config: "{{ ((lookup('file','{{playbook_dir}}/host_vars/{{inventory_hostname}}.yml')) | from_yaml) }}"

      - name: Check pool
        bigip_command:
          server: "{{ inventory_hostname }}"
          user: "{{ remote_username }}"
          password: "{{ remote_passwd }}"
          commands:
            - "list ltm pool {{ item }}"       
          validate_certs: no
        with_items:
            - "{{ device_config.pre_checks | json_query('checks.pool[*].name') }}"
        delegate_to: localhost
        when: "'active' in Active_LTM['stdout'][0]"
        register: Pre_Checks

      - name: Verify pool 
        debug: var=item
        with_items: "{{ Pre_Checks.results | map(attribute='stdout_lines') | list }}"