10

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?

5
  • what changes between your environments? Just the key file, or also the remote_user/sudo_user? Commented Apr 22, 2015 at 16:43
  • @tedder42 The SSH private key and remote_user. Commented Apr 22, 2015 at 16:46
  • Why don't you cover that in your .ssh/config? Commented Apr 22, 2015 at 16:51
  • @udondan Is there a way to specify a single key once for multiple hosts in .ssh/config? Commented Apr 22, 2015 at 17:07
  • Yes, you can do that. You can create multiple groups with explicit hostnames or patterns. Let me post an example in an answer. Commented Apr 22, 2015 at 17:35

1 Answer 1

17

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 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.