Search code examples
amazon-web-servicesamazon-ec2sshansibleansible-inventory

Using multiple SSH keys for different hosts with Ansible EC2 Inventory Plugin


I am trying to use Ansible to install applications across a number of existing AWS EC2 instances which use a number of different SSH keys and usernames on different Linux OSes. Because of the changing state of the existing instances I am attempting to use Ansible's Dynamic Inventory via the aws_ec2 inventory plugin as recommended.

I am able to group the hosts by key_name but now need to run the Ansible playbook against this inventory using the relevant SSH key and username according to the group, structured as the below example output from ansible-inventory -i inventory.aws_ec2.yml --graph:

@all:
  |--@_SSHkey1:
  |  |--hostnameA
  |  |--hostnameB
  |--@_SSHkey2:
  |  |--hostnameC
  |--@_SSHkey3:
  |  |--hostnameD
  |  |--hostnameE
  |  |--hostnameF
  |--@aws_ec2:
  |  |--hostnameA
  |  |--hostnameB
  |  |--hostnameC
  |  |--hostnameD
  |  |--hostnameE
  |  |--hostnameF
  |--@ungrouped:

I have tried creating a separate hosts file (as per the below) using the groups as listed above, providing the path to the relevant SSH key but I am unsure how you would use this with the dynamic inventory.

[SSHkey1]
ansible_user=ec2-user
ansible_ssh_private_key_file=/path/to/SSHkey1

[SSHkey2]
ansible_user=ubuntu
ansible_ssh_private_key_file=/path/to/SSHkey2

[SSHkey3]
ansible_user=ec2-user
ansible_ssh_private_key_file=/path/to/SSHkey3

This is not explained in the official Ansible documentation here and here but should be a common use case. A lot of the documentation I have found refers to an older method of using Dynamic Inventory using a python script (ec2.py) which is deprecated and so is no longer relevant (for instance this AWS post). I have found a similar unanswered question here (Part 3).

Any links to examples, documentation or explanations would be greatly appreciated as this seems to be a relatively new way of creating a dynamic inventory and I am finding it hard to locate clear, detailed documentation.


Edit

Using group variables as suggested by @larsks in the comments worked. Was initially caught out by the fact that the SSH key names returned from the inventory plugin prepend an underscore so the group names need to be of the form _SSHkey.


Solution

  • The answer was to use group variables as suggested in the comments. SSH key names returned from the inventory plugin prepend an underscore so the group names need to be of the form _SSHkey.