Replacing value of list elements with info from another variable

JethCalark
Thu, 19 Dec 2024 17:28:44 +0000
Get Help

Working on a role for Authentik; as with any IdP, I’m dealing with users and groups. Authentik gives an idempotent API path to use for updating groups, and it uses JSON for the body of its API calls, which is convenient, except in one way. To define which users are in a group, I have to list the users by their “pk” number, which is a random number assigned when the user was created in the system.

user_info_from_api_call:
# A previous task makes an API request for this info that I register to a variable.
    - name: Luke
      pk: 2843
    - name: ObiWan
      pk: 4973
    - name: Vader
      pk: 8693
    - name: Palpatine
      pk: 6666
desired_groups:
    - name: Jedi
      is_superuser: true
      users:
          - Luke
          - ObiWan
    - name: Sith
      is_superuser: false
      users:
          - Vader
          - Palpatine

Given the above variables, I need to transform desired_groups by replacing the user names with their pk numbers to plug into my API request to idempotently update the group:

# example desired outcome
desired_groups:
    - name: Jedi
      is_superuser: true
      users:
          - 2843
          - 4973
    - name: Sith
      is_superuser: false
      users:
          - 8693
          - 6666

I tried using items2dict on user_info_from_api_call to make it easier to reference the pk number by the user’s name, then using map() on desired_groups, but couldn’t make it gel. I appreciate any solutions people might have.

5 posts - 4 participants