Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible delegate_to how to set user that is used to connect to target?

I have an Ansible (2.1.1.) inventory:

build_machine ansible_host=localhost ansible_connection=local
staging_machine ansible_host=my.staging.host ansible_user=stager

I'm using SSH without ControlMaster.

I have a playbook that has a synchronize command:

- name: Copy build to staging
  hosts: staging_machine
  tasks:
    - synchronize: src=... dest=...
      delegate_to: staging_machine
      remote_user: stager

The command prompts for password of the wrong user:

local-mac-user@my-staging-host's password:

So instead of using ansible_user defined in the inventory or remote_user defined in task to connect to target (hosts specified in play), it uses the user that we connected to delegate-to box as, to connect to target hosts.

What am I doing wrong? How do I fix this?

EDIT: It works in 2.0.2, doesn't work in 2.1.x

like image 824
RokL Avatar asked Jul 29 '16 13:07

RokL


1 Answers

The remote_user setting is used at the playbook level to set a particular play run as a user.

example:

---
- hosts: webservers
  remote_user: root

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf

If you only have a certain task that needs to be run as a different user you can use the become and become_user settings.

- name: Run command
  command: whoami
  become: yes
  become_user: some_user

Finally if you have a group of tasks to run as a user in a play you can group them with block

example:

- block:
    - name: checkout repo
      git:
        repo: https://github.com/some/repo.git
        version: master
        dest: "{{ dst }}"
    - name: change perms
      file:
      dest: "{{ dst }}"
      state: directory
      mode: 0755
      owner: some_user
  become: yes
  become_user: some user

Reference: - How to switch a user per task or set of tasks? - https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html

like image 54
ecaepp Avatar answered Oct 22 '22 08:10

ecaepp