title: Specifying ssh key in ansible playbook file
body: <p>Ansible playbook can specify the key used for ssh connection using <code>--key-file</code> on the command line.</p>
  
  <pre><code>ansible-playbook -i hosts playbook.yml --key-file "~/.ssh/mykey.pem"
  </code></pre>
  
  <p>Is it possible to specify the location of this key in playbook file instead of using <code>--key-file</code> on command line?</p>
  
  <p>Because I want to write the location of this key into a <code>var.yaml</code> file, which will be read by ansible playbook with <code>vars_files:</code>.</p>
  
  <p>The followings are parts of my configuration:</p>
  
  <p>vars.yml file</p>
  
  <pre><code>key1: ~/.ssh/mykey1.pem
  key2: ~/.ssh/mykey2.pem
  </code></pre>
  
  <p>playbook.yml file</p>
  
  <pre><code>---
  
  - hosts: myHost
    remote_user: ubuntu
    key_file: {{ key1 }}  # This is not a valid syntax in ansible. Does there exist this kind of directive which allows me to specify the ssh key used for this connection?
    vars_files:
      - vars.yml
    tasks:
      - name: Echo a hello message
        command: echo hello
  </code></pre>
  
  <p>I've tried adding <code>ansible_ssh_private_key_file</code> under <code>vars</code>. But it doesn't work on my machine.</p>
  
  <pre><code>vars_files:
    - vars.yml
  vars:
    ansible_ssh_private_key_file: "{{ key1 }}"
  tasks:
    - name: Echo a hello message
      command: echo hello
  </code></pre>
  
  <p>If I run <code>ansible-playbook</code> with the <code>playbook.yml</code> above. I got the following error:</p>
  
  <pre><code>TASK [Gathering Facts] ******************************************************************************************************************************
  Using module file /usr/local/lib/python2.7/site-packages/ansible/modules/system/setup.py
  &lt;192.168.5.100&gt; ESTABLISH SSH CONNECTION FOR USER: ubuntu
  &lt;192.168.5.100&gt; SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ubuntu -o ConnectTimeout=10 -o ControlPath=/Users/myName/.ansible/cp/2d18691789 192.168.5.100 '/bin/sh -c '"'"'echo ~ &amp;&amp; sleep 0'"'"''
  &lt;192.168.5.100&gt; (255, '', 'Permission denied (publickey).\r\n')
  fatal: [192.168.5.100]: UNREACHABLE! =&gt; {
      "changed": false,
      "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n",
      "unreachable": true
  }
      to retry, use: --limit @/Users/myName/playbook.retry
  </code></pre>
  
  <p>I don't find the name of my key file in the ssh command. It's strange.</p>