基于平台的Ansible条件用户

Pet*_*ter 3 ansible ansible-playbook

我希望根据平台使用不同的用户来运行ansible playbook.

例如,我有一个像这样的剧本:

---
- hosts: all
  user: deploy
  tasks:
  - name: hello world
    shell: echo "Hello World"
Run Code Online (Sandbox Code Playgroud)

我希望该用户在RedHat上运行时"部署",在Darwin/Mac系统上运行环境变量$ USER.

我该如何设置?

ted*_*r42 6

在serverfault上有一个很好的问题,可以通过以下几种方式解决这个问题:ansible playbook,不同用户的操作系统,但它不是重复的,因为它是一个不同的"板".

这也是Ansible FAQ中的首要问题,如何处理需要不同用户帐户或端口登录的不同机器?,建议将其放入主机文件中ansible_ssh_user.

"Ansible最佳实践"的文件建议使用group_vars,这是最干净的选择.

对于琐碎的情况,您还可以选择性地运行任务:

- name: run this on debian type systems
  debug msg="hello from debian"
  sudo: yes
  sudo_user: ubuntu
  when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'

- name: run this on OSX type systems
  sudo: yes
  sudo_user: "{{ lookup('env','USER') }}"
  debug: msg="hello from osx"
  when: ansible_distribution == 'MacOSX'
Run Code Online (Sandbox Code Playgroud)

  • 我发现 `ansible_os_family` 更适合与 `when` 一起使用,因为 `ansible_os_family == 'Debian'` 涵盖了 Ubuntu 和 Linux Mint 等。 (2认同)