user vs sudo vs sudo_user in ansible playbooks

Solution 1:

  • user is the user you're ssh'ing as. With your config, you're ssh'ing as deploy.

  • sudo_user is the user you're sudo'ing on the host when sudo: yes is set.

So I think in your case none of sudo and sudo_user are necessary if you can ssh as deploy.

However, if you ssh as root, you need to set sudo_user: deploy and sudo: yes.

If you ask for 'sudo' but don't specify any user, Ansible will use the default set in your ~/.ansible.cfg (sudo_user), and will default to root.

Note that user is deprecated (because it's confusing). You should use remote_user instead.

EDIT: Case #2 probably hangs because of ssh confirmation issues : you probably have bitbucket.org host key in ~deploy/.ssh/known_hosts but NOT in ~root/.ssh/known_hosts

UPDATE: As of Ansible 2.x, use become and become_user instead of the deprecated sudo and sudo_user. Example usage:

- hosts: all
  user: deploy
  become: true
  become_user: deploy

  tasks:
      - name: Ensure code directory
        file: dest=/home/deploy/code state=directory

      - name: Deploy app
        git: [email protected]:YAmikep/djangotutorial.git dest=/home/deploy/cod