title: Ansible - switch ssh user (retaining keys in agent)
body: <p>I am a dev and want to use ansible to create dev-setups in VMs for various projects (one VM per project). VM manager commands are used to create a VM from a template, the template contains a stock OS install (typically Linux) with one addition: a public ssh-key specifically for use with ansible has been placed in the VM root user's <code>.ssh/authorized_keys</code> file. Global vars are then used to set ssh config:</p>
  
  <pre><code>ansible_user: root 
  ansible_private_key_file: keys/id_rsa_ansible
  </code></pre>
  
  <p>Then my <code>ansible.cfg</code> contains some entries for ssh-agent setup:</p>
  
  <pre><code>[ssh_connection]
  ssh_args = -o ForwardAgent=yes -o ControlMaster=auto -o ControlPersist=60s
  </code></pre>
  
  <p>With this setup I can launch ansible scripts to perform a number of root tasks such as installing packages &amp; creating user accounts for a set of devs.</p>
  
  <p>On the VM host I am logged in using my dev-users account, say <code>mike</code>. The ssh-agent setup also ensures that all ssh-keys loaded for user <code>mike</code> are also available in the VM through the ssh connection.</p>
  
  <p>I now want to perform further, dev-specific tasks as user <code>mike</code> on the VM (whose account now exists). The main task is to check out the project code which requires <code>mike</code>s ssh-key. </p>
  
  <p>Using <code>become</code> uses sudo, which does not forward ssh-keys, so this is not an option. I do not want to push private keys around as they would need to be on the host .. and no longer be private.</p>
  
  <p>The following now determines the devs username on the host &amp; uses it in an ssh command to achieve the checkout. This nicely restricts access to those projects the dev users key works for without further config.</p>
  
  <pre><code>- name: get the devs username running the deploy
    become: false
    local_action: command whoami
    register: username_on_the_host
  
  - name: Test checkout
    command: ssh -o StrictHostKeyChecking=no -o ForwardAgent=yes {{ username_on_the_host.stdout }}@localhost "mkdir hg &amp;&amp; cd hg &amp;&amp; hg clone ssh://hg//hg/my_project"
  </code></pre>
  
  <p>It works, but it's not a particularly clean solution. </p>
  
  <p>So, finally to come to the question: Is there a cleaner way to switch ssh-session? One way might be to run a totally separate playbook with an ssh-session for the dev user - but this does not seem to be in the spirit of ansible. I want to run an entire block, task, or role as a different <em>ssh</em> user.</p>
  
  <p>This could be achieved if the <code>become</code> module were to support <code>become_method</code> <code>ssh</code> which would retain the ssh-keys in the agent.</p>