简体   繁体   中英

Loop on Ansible items

I have the following data as input:

list_domains:
  domain1:
    server_name: "domain1.com"
    server_alias:
      - "domain1.fr"
    certificate:
      method: "webroot"
    php_custom_values:
      memory_limit: "128M"
    database:
      type: "mysql"
    cms:
      type: "prestashop"
  domain2:
    server_name: domain2.com
    php_custom_values:
      memory_limit: "512M"

To create many domains on many hosts.

I use this loop to create all domains configurations:

tasks:
  - name: "Create domain configuration"
    include_role:
      name: webserver/domain
    loop: "{{ list_domains| dict2items }}"
    loop_control:
      loop_var: domain

But I'd like to update only one domain configuration when the playbook is run with a domain name as extra variable

For example:

ansible-playbook domains.yml -e target=domain1

But I didn't manage to extract one item in the dict and use it in the role.

In a nutshell to put you on track

---
- name: Not fully tested example only playbook
  hosts: localhost
  gather_facts: false

  vars:

    # Your original data
    list_domains: <your full dict as in example>

    # The loopable list of domains
    my_list: "{{ list_domains| dict2items }}"

  tasks:

    - name: Filter out the list if target is defined
      set_fact:
        my_list: "{{ my_list | selectattr('key', '==', target) }}"
      when: target is defined

    - name: Do the job with the list
      include_role:
        name: webserver/domain
      loop: "{{ my_list }}"
      loop_control:
        loop_var: domain

Adding | list | list makes the job

Here is the complete filter:

    - name: Filter out the list if target is defined
  set_fact:
    my_list: "{{ my_list | selectattr('key', '==', target) | list }}"
  when: target is defined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM