【问题标题】:How to run a playbook task based on OS type in ansible?如何在ansible中根据操作系统类型运行剧本任务?
【发布时间】:2019-02-07 12:06:53
【问题描述】:

我在 ansible 中编写了一个剧本任务。我可以在 linux 端运行 playbook。

- 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

在 linux 中,我们在主目录中有 .profile,但在 Mac 中,在 macOS 中没有 .profile.bash_profile

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

我已经尝试添加

when: ansible_distribution == 'Ubuntu' and ansible_distribution_release == 'precise'

但它首先不起作用,而且它是长度过程。我想在变量中获取基于 os 的路径并使用它。

谢谢

【问题讨论】:

    标签: linux macos shell ansible


    【解决方案1】:

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

    谢谢

    【讨论】:

      【解决方案2】:

      一个选项是从文件中include_vars。请参阅下面的示例

      - name: "OS specific vars (will overwrite /vars/main.yml)"
        include_vars: "{{ item }}"
        with_first_found:
          - files:
              - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
              - "{{ ansible_distribution }}.yml"
              - "{{ ansible_os_family }}.yml"
              - "default.yml"
            paths: "{{ playbook_dir }}/vars"
            skip: true
      
      - name: Set paths for go
        blockinfile:
          path: "$HOME/{{ my_profile_file }}"
      [...]
      

      在playbooks的目录下创建目录vars并创建文件

      # cat var/Ubuntu.yml
      my_profile_file: ".profile"
      
      # cat var/macOS.yml
      my_profile_file: ".bash_profile"
      

      【讨论】:

      • 我无法将其与我创建的上述剧本任务联系起来。你能把我发布的上述任务播放列表联系起来吗?因为我开始使用 Ansiblle
      • 这当然是解决问题的更好方法之一,但您可能需要通过示例扩展答案以使其与问题相关。
      • 我已经更新了答案。如果您遇到问题,请使用Minimal, Complete, and Verifiable example 更新您的问题
      【解决方案3】:

      如果您有不同操作系统的托管主机,请在清单中按操作系统对它们进行分组:

      [Ubuntu]
      ubu1
      ubu2
      
      [RHEL6]
      RH6_1
      
      [RHEL7]
      RH7_1
      RH7_2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-15
        • 2015-12-14
        • 2020-08-15
        • 1970-01-01
        • 1970-01-01
        • 2016-06-08
        相关资源
        最近更新 更多