Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible conditional user based on platform

Tags:

ansible

I want to have a different user to be used based on the platform an ansible playbook is run from.

For example I have a playbook like this:

---
- hosts: all
  user: deploy
  tasks:
  - name: hello world
    shell: echo "Hello World"

I want that user to be "deploy" when ran on a RedHat, and the environmental variable $USER on a Darwin/Mac system.

How would I set this up?

like image 645
Peter Souter Avatar asked Dec 25 '22 03:12

Peter Souter


1 Answers

There's a great question on serverfault that answers this in a few ways: ansible playbook, different user by operating system, but it's not a duplicate because it's a different "board".

It's also the top question in the Ansible FAQ, How do I handle different machines needing different user accounts or ports to log in with?, which suggests putting it in the host file with ansible_ssh_user.

The "Ansible best practices" file suggests using group_vars, which is the cleanest option.

For trivial cases, you can also selectively run tasks:

- 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'
like image 179
tedder42 Avatar answered Feb 09 '23 05:02

tedder42