devops's docs

1.3.8: playbook-include&loop error


0. 背景

github issue (必看)

特别需要注意的是,下面内容中的转义符"\"仅仅是为了兼容语法而存在,实际使用过程中,应该要去掉


1. warn信息

使用了两个yaml文件,通过include套用,而且两个yaml都有自己的循环

# outer yaml
---
- name: yum install libselinux-python
  yum: name=\{\{ item }} state=present
  with_items:
    - epel-release
    - libselinux-python
    - "@Development tools"
    - "@base"

- include: "\{\{ item }}.yml"
  with_items: "\{\{ server_type }}"

# inner yaml
---
- name: install env packages
  yum: name=\{\{ inner_item }} state=present
  with_items:
    - gcc
    - gcc-c++
    - cmake
    - ncurses-devel
    - pcre-devel
    - openssl
    - openssl-devel
---

执行时提示

TASK [server_initialize : install env packages] ********************************
 [WARNING]: The loop variable 'item' is already in use. You should set the `loop_var` value in the `loop_control` option for the task to something else to avoid variable
collisions and unexpected behavior.

2. 解决办法

给inner yaml的loop_control中配置一个不一样的loop_var

# inner yaml
---
- name: install env packages
  yum: name=\{\{ inner_item }} state=present
  with_items:
    - gcc
    - gcc-c++
    - cmake
    - ncurses-devel
    - pcre-devel
    - openssl
    - openssl-devel
  loop_control:
    loop_var: inner_item
---

其实这个bug已经被修复,以前这个bug会把outer yaml中的item变量传递给inner yaml,导致inner yaml中的item变量被覆盖,但是现在不会被覆盖了,不过还是推荐大家注意修改不同的循环变量,以防发生灵异事件