lonewolf
lonewolf

Reputation: 61

Placing Value of Key defined in other variables key-value - Ansible

I am trying a simple scenario of managing users and their respective authorized_key values where some user may have inter-shared authorized_keys, any quick help to avoid the repetation which may occur in following :

file: roles/manageuser/var/main.yml

---
users:
  - username: user1
    ssh_key: "someExampleValidRSAPublicKEYValueInHereForAuthorizedKeys user1@localhost"

  - username: user2
    ssh_key: |
      someExampleValidRSAPublicKEYValueInHereForAuthorizedKeys user2@localhost
      someExampleValidRSAPublicKEYValueInHereForAuthorizedKeys user1@localhost

In above, I want to avoid repasting or repetation of user1 public-key under user2 section and to place it in via some filter or query or lookup over user1, for example :

{{ query(users[?username=='user1'].ssh_key) }} - DOESN'T WORK

lookup('dict', ssh_key, users.username='user1') - DOESN'T WORK EITHER

Can anyone guide me through this to using it correctly? Please note that I am trying to seed in value inside var/main.yml, so not sure how feasible that is as well.

Thanks,

Upvotes: 1

Views: 112

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67984

It's not possible. Quoting from Can't reference a dict key inside the same dict #50280

"This is expected and not something that we plan on changing. You cannot create a self referential variable."


You might want to put the public keys into files and create an attribute with the list of lookups. For example

users:
  - username: user1
    ssh_keys:
      - "{{ lookup('file', 'user1.localhost.pub') }}"
  - username: user2
    ssh_keys:
      - "{{ lookup('file', 'user1.localhost.pub') }}"
      - "{{ lookup('file', 'user2.localhost.pub') }}"

There is no overhead here. You have to reference all keys for a user anyway. Transform the lists to any format you need.

Upvotes: 2

Related Questions