Specifying ssh key in ansible playbook file

The variable name you’re looking for is ansible_ssh_private_key_file.

You should set it at ‘vars’ level:

  • in the inventory file:

    myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
    myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
    
  • in the host_vars:

    # host_vars/myHost.yml
    ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
    
    # host_vars/myOtherHost.yml
    ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
    
  • in a group_vars file if you use the same key for a group of hosts

  • in the vars section of an entry in a play:

    - hosts: myHost
       remote_user: ubuntu
       vars_files:
         - vars.yml
       vars:
         ansible_ssh_private_key_file: "{{ key1 }}"
       tasks:
         - name: Echo a hello message
           command: echo hello
    
  • in setting a fact in a play entry (task):

    - name: 'you name it'
       ansible.builtin.set_fact:
         ansible_ssh_private_key_file: "{{ key1 }}"
    

Inventory documentation

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)