Ansible 2.5包含带变量的角色

时间:2018-06-20 17:01:39

标签: ansible ansible-2.x

ansible 2.5.5
...
 python version = 3.6.5 (default, Jun 17 2018, 12:26:58) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]

我正在尝试遍历角色并应用动态变量。

似乎变量从未应用,这意味着CLI变量不会像我希望的那样被覆盖...

这可能是可变优先级的事情吗?

我也在CLI中声明了变量service_nameversion,以尝试部署一项服务和多个相关服务。

tasks:
    - include_role:
        name: "check_deps"
    - debug:
        msg: "{{ item }}"
      loop: "{{ deps_info_list }}"

    - include_role:
        name: "ecs_service"
      vars:
        service_name: "{{depsvcitem.name}}"
        version: "{{depsvcitem.version}}"
      loop: "{{deps_info_list}}"
      loop_control:
        loop_var: depsvcitem

当我用...调用时

# args.yml
cluster: "devops-poc"
service_name: "bss-com-api-feed-validation"
version: "1.0.0.8"

和...

ansible-playbook playbooks/myplaybook.yml -e @args.yml 

上述循环中被调用角色的变量被获取  用args.yml的值覆盖,而不是用循环中的动态变量覆盖args.yml的值

1 个答案:

答案 0 :(得分:0)

该问题确实是变量优先级问题,因为在CLI上使用-e定义的变量具有优先级。

我解决的方法是更改​​CLI上定义的变量名:

from service_name to orig_service_name
from version to orig_version

然后在剧本中按需分配和取消分配角色变量,就像这样...

tasks:
# first we set the variables that the roles are looking for ...
- set_fact:
    service_name: "{{ orig_service_name }}"
    version: "{{ orig_version }}"

# Then we call the role that checks dependencies
- include_role:
    name: "check_deps"
- debug:
    msg: "{{ item }}"
  loop: "{{ deps_info_list }}"

# If we have dependencies
# and those dependencies are not running
# we create them in the below block
- block:
  # First make sure the the below variables are unset
  # so as to avoid variable precedence overwrites
  - set_fact:
      service_name: false
      version: false

  # For each non-existing or non-running service
  # we run the `ecs_service` role
  - include_role:
      name: "ecs_service"
    vars:
      service_name: "{{depsvcitem.name}}"
      version: "{{depsvcitem.version}}"
    loop: "{{deps_info_list}}"
    loop_control:
      loop_var: depsvcitem

  # Set the variables to what the `ecs_service` role needs
  # in preparation for creating the parent service
  - set_fact:
      service_name: "{{ orig_service_name }}"
      version: "{{ orig_version }}"

  when: deps_info_list|length|int > 0

# Create the parent or only service
- include_role:
    name: "ecs_service"