How to define and use the environment (production/development)?

I have different environments and for each an inventory: production.ini and development.ini.

I have a users.yml containing user data:

users:

  • username: foo
    uid: 1001
    gid: 1001
    pw_hash: $6$…
    ssh_key: ssh-rsa AAAA…

  • username: bar
    uid: 1002
    gid: 1002
    pw_hash: $6$…
    ssh_key: ssh-rsa AAAA…

I use the users in a user task.

user:
name: “{{ item.username }}”
uid: “{{ item.uid }}”
gid: “{{ item.gid }}”
with_items: “{{ users }}”

And I use the SSH keys in an authorized_key task.

authorized_key: user={{ item.username }} key={{ item.ssh_key }}
with_items: “{{ users }}”

This works in the production end development environment.

Now I have the requirement to use different SSH keys for some but not all users in production and development.

How to get the different SSH keys in the users.yml without duplicating all the remaining data for each environment?

My first idea was to make the ssh_key attribute a hash:

users:

  • username: foo
    uid: 1001
    gid: 1001
    pw_hash: $6$…
    ssh_key:
    production: ssh-rsa AAAA…

development: ssh-rsa BBBB…

By this I can select the right key based on the environment:

authorized_key: user={{ item.username }} key={{ item.ssh_key[environment] | default(item.ssh_key.production) }}
with_items: “{{ users }}”

But how to know in a playbook in which environment the playbook is executed?

How to get the different SSH keys in the users.yml without
duplicating all the remaining data for each environment?

group_vars would be another idea.

But how to know in a playbook in which environment the playbook is
executed?

Setting a variable? If you set this variable inside your different
variable files, then you could use this variable to get the right item
out of the hash.

I.e. set 'foobar=production' in your production variable file, and
then use the value of foobar to get the right hash.

Or am I missing a bit here?

Johannes

I got the idea. It is explained here:

https://www.digitalocean.com/community/tutorials/how-to-manage-multistage-environments-with-ansible