2

I have a dictionary like this

customers:
  abc:
    id: 1
    status: active
  def:
    id: 2
    status: inactive
  ghi:
    id: 3
    status: active
  jkl:
    id: 4
    status: active

What's the best way to construct a string like below of the active customers only?

abc,ghi,jkl

2 Answers 2

3

For example:

---
- hosts: localhost
  gather_facts: no
  vars:
    customers:
      abc:
        id: 1
        status: active
      def:
        id: 2
        status: inactive
      ghi:
        id: 3
        status: active
      jkl:
        id: 4
        status: active
  tasks:
    - debug:
        msg: "{{ customers | dictsort | selectattr('1.status','equalto','active') | map(attribute='0') | join(',') }}"
Sign up to request clarification or add additional context in comments.

2 Comments

One more question, how can I also append a string (e.g. cust_) so the output looks like this? cust_abc,cust_ghi,cust_jkl
Add map('regex_replace','^','cust_') before join
0

Not exactly what you asked for, but I think this might add value to the question.

In my case, I needed to join a list of items using a space.

defaults/main.yml

---
backup_dev_strip:
  - "@stripped"
  - "@development"

vars/main.yml

---
backup_dev_strip_merged: "{{ backup_dev_strip | join(' ') }}"

As a result

TASK [... : debug] 
ok: [...] => {
    "backup_dev_strip_merged": "@stripped @development"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.