Bootstrap FreeKB - Ansible - module_defaults parameter
Ansible - module_defaults parameter

Updated:   |  Ansible articles

Let's say you are calling a module many times with similar parameters. In this example, ansible.builtin.copy is being called a few times, with similar parameters.

---
- hosts: all
  tasks:
  - name: copy foo.txt
    ansible.builtin.copy:
      src: /tmp/foo.txt
      dest: /tmp/foo.txt
      owner: john.doe
      group: john.doe
      mode: "0644"

  - name: copy bar.txt
    ansible.builtin.copy:
      src: /tmp/bar.txt
      dest: /tmp/bar.txt
      owner: john.doe
      group: john.doe
      mode: "0644"

  - name: copy foobar.txt
    ansible.builtin.copy:
      src: /tmp/foobar.txt
      dest: /tmp/foobar.txt
      owner: john.doe
      group: john.doe
      mode: "0644"

 

module_defaults can be used to define default parameters for another module. In this example, module_defaults is defined at the play level, before pre_tasks and tasks.

---
- hosts: all
  module_defaults:
    ansible.builtin.copy:
        owner: john.doe
        group: john.doe
        mode: "0644"
  tasks:
  - name: copy foo.txt
    ansible.builtin.copy:
      src: /tmp/foo.txt
      dest: /tmp/foo.txt

  - name: copy bar.txt
    ansible.builtin.copy:
      src: /tmp/bar.txt
      dest: /tmp/bar.txt

  - name: copy foobar.txt
    ansible.builtin.copy:
      src: /tmp/foobar.txt
      dest: /tmp/foobar.txt

 

In this example, module_defaults is defined in pre_tasks.

---
- hosts: all
  pre_tasks:
  module_defaults:
    ansible.builtin.copy:
        owner: john.doe
        group: john.doe
        mode: "0644"
  tasks:
  - name: copy foo.txt
    ansible.builtin.copy:
      src: /tmp/foo.txt
      dest: /tmp/foo.txt

  - name: copy bar.txt
    ansible.builtin.copy:
      src: /tmp/bar.txt
      dest: /tmp/bar.txt

  - name: copy foobar.txt
    ansible.builtin.copy:
      src: /tmp/foobar.txt
      dest: /tmp/foobar.txt

 

In this example, module_defaults is defined in tasks with blocks.

---
- hosts: all
  tasks:
  - module_defaults:
      ansible.builtin.copy:
        owner: john.doe
        group: john.doe
        mode: "0644"  

    block:
    - name: copy foo.txt
      ansible.builtin.copy:
        src: /tmp/foo.txt
        dest: /tmp/foo.txt

    - name: copy bar.txt
      ansible.builtin.copy:
        src: /tmp/bar.txt
        dest: /tmp/bar.txt

    - name: copy foobar.txt
      ansible.builtin.copy:
        src: /tmp/foobar.txt
        dest: /tmp/foobar.txt

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 801fa2 in the box below so that we can be sure you are a human.