如何在ansible中根据操作系统类型运行playbook任务?

Tec*_*ain 1 linux macos shell ansible

我用 ansible 编写了一个剧本任务。我能够在 Linux 端运行该剧本。

- name: Set paths for go
      blockinfile:
        path: $HOME/.profile
        backup: yes
        state: present
        block: |
          export PATH=$PATH:/usr/local/go/bin
          export GOPATH=$HOME/go
          export FABRIC_CFG_PATH=$HOME/.fabdep/config

    - name: Load Env variables
      shell: source $HOME/.profile
      args:
        executable: /bin/bash
      register: source_result
      become: yes
Run Code Online (Sandbox Code Playgroud)

与在 Linux 中一样,我们.profile在主目录中有,但在 Mac 中没有.profile,而.bash_profile在 macOS 中。

所以我想检查操作系统是否是Mac,那么路径应该是$HOME/.bash_profile,如果操作系统是基于Linux的,那么它应该寻找$HOME/.profile.

我尝试过添加

when: ansible_distribution == 'Ubuntu' and ansible_distribution_release == 'precise'
Run Code Online (Sandbox Code Playgroud)

但这首先行不通,而且是一个漫长的过程。我想获取基于变量中操作系统的路径并使用它。

谢谢

Tec*_*ain 5

我通过这种方式找到了解决方案。我gather_facts:true在 yaml 文件顶部添加了它,它开始工作。我开始使用变量 as ansible_distribution

谢谢