Ansible Amazon EC2. The key pair does not exist

The key parameter for the ec2 module is looking for the key pair name that has been already uploaded to AWS, not a local key.

If you want to get Ansible to upload a public key you can use the ec2_key module.

So your playbook would look like this:

--
- name: Setup servers on Amazon EC2 machines
  hosts: localhost
  gather_facts: no

  tasks:
    - include_vars: group_vars/all/ec2_vars.yml

    ### Create Amazon EC2 key pair
    - name: Amazon EC2 | Create Key Pair
      ec2_key:
        name: "{{ key_name }}"
        region: "{{ region }}"
        key_material: "{{ item }}"
      with_file: /path/to/public_key.id_rsa.pub

    ### Create Amazon EC2 instances
    - name: Amazon EC2 | Create instances
      ec2:
        count: "{{ count }}"
        key_name: "{{ key_name }}"
        ...

Do not specify extension for the key. So that key name should be " EC2-Kibi-Enterprise-Deployment " only. Ansible doesn't care if your key is on your local machine at this stage. It verifies if it exists on your AWS account. Go to 'EC2 > Key Pairs' section in your AWS account and you'll see keys are listed without file extensions.


The solution has been found. EC2 doesn't like when you put a full path for the .pem key file.

So, I moved EC2-Kibi-Enterprise-Deployment.pem into ~/.ssh, added it to the authentication agent with ssh-add using:

ssh-add ~/.ssh/EC2-Kibi-Enterprise-Deployment.pem

And corrected the key line in my var file to
key: EC2-Kibi-Enterprise-Deployment.pem

The same if you use EC2 cli tools, don't specify a full path to the key file.
ec2-run-instances ami-d1ec01a6 -t t2.medium --region eu-west-1 --key EC2-Kibi-Enterprise-Deployment.pem