与用户定义条件的 Ansible 依赖关系

问题描述 投票:0回答:1

我想在我的剧本依赖项中添加一个角色,但要基于条件。

- name: Get all install pyenv versions
  command: '{{ pyenv_root }}bin/pyenv versions'
  register: available_versions
  tags:
      - get_pyenv_versions
  environment:
      PYENV_ROOT: "{{ pyenv_root }}"

dependencies:
    - { role: pyenv, python_versions: ["{{ mypython_version }}"], when: "mypython_version not in available_versions.stdout" }

我想做的是,我想检查所有可用的

pyenv
版本,如果
mypython_version
不可用,那么只有我想调用
pyenv
角色,否则我不想调用它。

它给了我语法错误

ERROR! Syntax Error while loading YAML.


The error appears to have been in '/root/ansible_playbooks/roles/mydeployment/meta/main.yaml': line 9, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


dependencies:
^ here

exception type: <class 'yaml.parser.ParserError'>
exception: while parsing a block collection
  in "<unicode string>", line 1, column 1
did not find expected '-' indicator
  in "<unicode string>", line 9, column 1

如何定义变量

get_pyenv_versions
并在我的
dependencies
中用作条件?

ansible dependencies
1个回答
5
投票

要正确定义角色中的依赖关系,您必须:

在您的角色下定义 /meta/main.yml 依赖项:

dependencies:
  - role: pyenv
    when: mypython_version not in versions

你必须从你的戏剧中调用你的角色:

---
- name: Role Dependency
  hosts: localhost
  gather_facts: False

tasks:
  - name: Get all install pyenv versions
    command: '{{ pyenv_root }}bin/pyenv versions'
    register: available_versions
    environment:
      PYENV_ROOT: "{{ pyenv_root }}"

roles:
  - role: mydeployment
    pyenv_version : "{{ mypython_version }}"
    versions      : "{{ available_versions.stdout }}"

我的沙箱中的另一个例子:

---
- name: Role Dependency
  hosts: localhost
  gather_facts: False

  roles:
  - role: role2
    role1 : "Heyr"

元:

dependencies:
  - role: role1
    when: role1 == "Hey"

结果:

PLAY [Role Dependency] *******************************************************************************************************

TASK [role1 : Debug] *********************************************************************************************************
skipping: [localhost]

TASK [role2 : Debug] *********************************************************************************************************
ok: [localhost] => {
    "msg": "Hello2"
}

但是当变量很好时:

---
- name: Role Dependency
  hosts: localhost
  gather_facts: False

  roles:
  - role: role2
    role1 : "Heyr"

结果:

TASK [role1 : Debug] *********************************************************************************************************
ok: [localhost] => {
    "msg": "Hello1"
}

TASK [role2 : Debug] *********************************************************************************************************
ok: [localhost] => {
    "msg": "Hello2"
}

希望有帮助

© www.soinside.com 2019 - 2024. All rights reserved.