-1

I have a list:

awx_credentials:
  - name: "user1"
    password: "123"
  - name: "user2"
    password: "123"
  - name: "user3"
    password: "123"
  - name: "user4"
    password: "123"

In one task I need to get the name of the user2 name like this:

- name: "My test"
  awx.awx.execution_environment:
  name: "My EE"
  image: "quay.io/ansible"
  credential: "{{ awx_credentials[1].name }}"

But if I change the order of the list, this will not work.

How could I get the value of name searching for user2 into the list?

Thank you in advance!

Zeitounator
  • 38,476
  • 7
  • 53
  • 66
Costales
  • 2,799
  • 1
  • 17
  • 21
  • 2
    => `{{ awx_credentials | selectattr('name', '==', 'user2') | map(attribute='name') | first }}` but this is an overkill as the result is the same thing as hardcoding `"user2"` directly. – Zeitounator Jan 26 '23 at 08:25

2 Answers2

1
Given the data for testing
  awx_credentials:
    - {name: user1, password: A}
    - {name: user2, password: B}
    - {name: user3, password: C}
    - {name: user4, password: D}

This is a typical case of wrong data structure. In the list awx_credentials, the values of the attribute name are unique. A better data structure is a dictionary. If you have to use the list convert it to a dictionary first

  awx_credentials_dict: "{{ awx_credentials|
                            items2dict(key_name='name',
                                       value_name='password') }}"

gives

  awx_credentials_dict:
    user1: A
    user2: B
    user3: C
    user4: D

Then, looking for the passwords is trivial.

See: In Python, when to use a Dictionary, List or Set?

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
0

I assume that you would like to search dynamically for usernames and mostly like to get the password since the username is already given.

A minimal example playbook which will lookup the password for a given user.

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    credentials:
    - name: "user1"
      password: "pwd1"
    - name: "user2"
      password: "pwd2"
    - name: "user3"
      password: "pwd3"
    - name: "user4"
      password: "pwd4"

    USER: "user2"

  tasks:

  - name: My test
    debug:
      msg: "{{ credentials[1].password }}"

  - name: Other test
    debug:
      msg: "{{ credentials | selectattr('name', '==', USER) | map(attribute='password') | first }}"

... and based on the comment of Zeitounator

The variable for the user could even be

{{ credentials | selectattr('name', '==', ansible_user) | map(attribute='password') | first }}

to make automation and execution easier.

Further Documentation

U880D
  • 8,601
  • 6
  • 24
  • 40