简体   繁体   中英

Ansible block vars

How can I set in Ansible block vars (visible only for tasks in block) ?

I tried:

---
- hosts: test
  tasks:
    - block:

       - name: task 1
         shell: "echo {{item}}"

      with_items:
        - one
        - two

but it seems that it's a wrong way.

  • If you want to define a variable for a block:

     - block: - debug: var: var_for_block vars: var_for_block: "value for var_for_block" 
  • If you want to "loop over blocks" as your code suggests - you can't. It's not implemented in Ansible. Follow this thread .

    For now consider saving the tasks to a separate file and use include instead.

@Shasha99 you might be able to include a file with a block in it so you can still benefit from the try/catch

includeFile.yml :

- block
    - name: Finding the package.
      shell: rpm -qa | grep "{{pkgName}}"
      register: package

    - name: Uninstalling the package.
      shell: rpm -e "{{package}}"
  always:
    - debug: msg="this always executes"

main.yml:

---
- hosts: all
  vars: 
    - packageList : ["pkg1","pkg2","pkg3","pkg4"]

  tasks:
    - include: includeFile.yml pkgName="{{item}}"
      with_items: packageList

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