Search code examples
linuxansiblesudo

ansible become method - change between hosts


lets say I have a playbook:

---
- name
  host: testserver
  become_method = sudo
  become_user = root
  tasks:
    - name: copystuff
      module: copy
        do stuff
    - name: copy stuff
      delegate_to: localhost
      module: copy
        do stuff 

I have same user with the same password on both localhost and the testserver. But on testserver, I have to use sudo to beocme a root but on localhost I have to use dzdo to become a root.

So I was wondering if there is a way for me use either one, if one method does not work?


Solution

  • Yes, that's what hostvars are designed to do: declare vars per host.

    You can do that in your inventory file, as shown in the fine manual, if you have an inventory file (or in most dynamic inventory sources). Or, if you are running with a more ad-hoc inventory list (such as -i machine1,localhost,machine99) then you can use a conditional set_fact: to declare that hostvar after ansible has started running:

    - set_fact:
        ansible_become_method: dzdo
      when: inventory_hostname == "localhost"
    

    so long as you do that before using a task that has become: yes on it

    The pre_tasks: keyword may interest you, too