shell 如何在ansible中基于操作系统类型运行playbook任务?

kqhtkvqz  于 2023-08-07  发布在  Shell
关注(0)|答案(4)|浏览(107)

我用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中没有.profile.bash_profile
所以我想检查如果os是Mac,那么path应该是$HOME/.bash_profile,如果os是基于Linux的,那么它应该查找$HOME/.profile
我试着添加

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


但它并不是一开始就起作用的,而且它是一个漫长的过程。我想在变量中获取基于os的路径并使用它。
谢啦,谢啦

btqmn9zl

btqmn9zl1#

我找到了一个解决办法。我在yaml文件的顶部添加了gather_facts:true,它开始工作了。我开始使用变量ansible_distribution
谢啦,谢啦

n8ghc7c1

n8ghc7c12#

另一种方法是将条件when添加到正在讨论的任务中。举例来说:

- name: Install a few more tools
  become: yes
  apt:
    state: latest
    pkg:
    - bat
    - ripgrep
  when:
  - ansible_facts['distribution'] == "Ubuntu" or ansible_facts['distribution'] == 'Pop!_OS'
  - ansible_facts['distribution_major_version'] >= "20"

字符串
上面的示例仅在操作系统为Ubuntu或Pop!_OS,并且OS主版本为20或更高版本。

rfbsl7qr

rfbsl7qr3#

一个选项是从文件中 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"

1tuwyuhd

1tuwyuhd4#

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

[Ubuntu]
ubu1
ubu2

[RHEL6]
RH6_1

[RHEL7]
RH7_1
RH7_2

字符串

相关问题