为幂等任务运行添加条件到 Ansible 角色

Add Conditionals to Ansible Role for Idempotent Tasks Runs

我已经搜索了很长时间,并尝试了很多变体和类似的答案,但都没有成功。希望这是我所缺少的简单东西。

Ansible 2.9.6

我正在创建许多剧本,它们都为我的客户共享大量自定义角色。我想将所有逻辑都排除在剧本之外,并将该逻辑放在角色本身中以实现最大的可重用性。基本上,我只想为通过标签运行的简单 "Role" 添加样板剧本,并在此处和那里覆盖一些变量。

我的问题是我似乎无法通过使用条件使某些角色幂等 - 条件不起作用。我得到的错误是:

fatal: [localhost]: FAILED! => {"msg": "The conditional check 'homebrew_base.rc != 0' failed.
The error was: error while evaluating conditional (homebrew_bash.rc != 0): 'homebrew_bash' is undefined

The error appears to be in '/Users/eric/code/client1/provisioning/roles/bash/tasks/main.yaml': line 12, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: Change shell (chsh) for macOS to homebrew managed version
  ^ here
"}

下面是我的剧本的样板代码:

# ./playbook.yaml

---
- name: Provisioning
  hosts: localhost
  connection: local

  pre_tasks:
    - include_vars: "{{ item }}"
    with_fileglob:
      - "{{ playbook_dir }}/vars/global.yaml"
  tags: always

tasks:

  - name: Use homebrew bash binary
    include_role:
      name: bash
    tags: bash

上面的内容被截断了很多,但唯一缺少的是额外的 var 文件和一大堆 include_roles。

下面是我的完整角色文件。由于我不断收到错误,它们在很大程度上未经测试。

# ./roles/bash/tasks/main.yaml

---
- name: Check /etc/shells contains "/usr/local/bin/bash"
  command: grep -Fxq "/usr/local/bin/bash" /etc/shells
  register: homebrew_bash
  ignore_errors: True
  changed_when:
    - homebrew_bash.rc != 0

- name: Check that homebrew installed /usr/local/bin/bash
  stat:
    path: /usr/local/bin/bash
  register: homebrew_bash_binary

- name: Change shell (chsh) for macOS to homebrew managed versoin
  tags: bash, chsh
  shell: chsh -s /usr/local/bin/bash
  become: yes
  when:
    - homebrew_bash.rc != 0
    - homebrew_bash_binary.stat.exists = True

Ps:我计划将这些硬编码路径抽象为 roles/bash/defaults/。但在那之前我需要它先工作。

Ps2:如果有更好的方法来使用包含过滤器(而不是 grep hack),我洗耳恭听。

我试过:

同样,我试图只在角色中保留这种逻辑,而不是在剧本中。

谢谢!

想通了。我在条件句中遗漏了 "tags"!

# ./roles/bash/tasks/main.yaml

---
- name: Check /etc/shells contains "/usr/local/bin/bash"
  tags: bash, chsh
  command: grep -Fxq "/usr/local/bin/bash" /etc/shells
  register: homebrew_bash
  ignore_errors: True
  changed_when:
    - homebrew_bash.rc != 0

- name: Check that homebrew installed /usr/local/bin/bash
  tags: bash, chsh
  stat:
    path: /usr/local/bin/bash
  register: homebrew_bash_binary

- name: Change shell (chsh) for macOS to homebrew managed versoin
  tags: bash, chsh
  shell: chsh -s /usr/local/bin/bash
  become: yes
  when:
    - homebrew_bash.rc != 0
    - homebrew_bash_binary.stat.exists = True