Ssh – Configure SSH credentials per environment

ansiblessh

I'm trying to figure out how to configure the SSH credentials separately for a production and staging environment with Ansible. I understand that you can configure the server IP addresses and hostnames separately using different inventory files by passing the -i or --inventory-file argument to the ansible-playbook command. However, I see no such option for ansible.cfg. Currently, the credentials live in /etc/ansible/ansible.cfg as:

[defaults]
private_key_file=/home/caleb/.ssh/staging_key.pem
remote_user=ubuntu
sudo_user=root
gathering=explicit

How can I configure multiple SSH credentials, one for production and one for staging?

Best Answer

Seems like my first answer was not entirely correct. While of course it is possible to solve it in your .ssh/config like described below, it seems as well to be possible with Ansibles Behavioral Inventory Parameters.

You should (according to docs) be able to define the keyfile and the user in your inventory, either per host or per group.

Definition per group:

[some_hosts]
host1.foo
host2.foo

[some_hosts:vars]
ansible_ssh_user=ubuntu
ansible_ssh_private_key_file=/home/caleb/.ssh/staging_key.pem

Definition per host:

[some_hosts]
host1.foo     ansible_ssh_user=ubuntu          ansible_ssh_private_key_file=/home/caleb/.ssh/staging_key.pem
host2.foo     ansible_ssh_user=another_user    ansible_ssh_private_key_file=/home/caleb/.ssh/production_key.pem

But you can define multiple host groups already in your .ssh/config and each group can have their separate settings regarding key and user.

Here is a quick example

#Example with a wildcard
Host *.foo.com
  user ubuntu
  IdentityFile /home/caleb/.ssh/staging_key.pem

#Example with multiple hostnames
Host hostname.one hostname.two hostname.three
  user other_user
  IdentityFile /home/caleb/.ssh/production_key.pem

As well you could define a default and override it later with more detailed settings.

Host *
  user defaut_username

Host somehost
  user special_username