Jinja: 지도 ν•„ν„°κ°€ μ—¬λŸ¬ ν•­λͺ©μ„ κ²€μƒ‰ν•˜λ„λ‘ ν—ˆμš©

에 λ§Œλ“  2016λ…„ 02μ›” 29일  Β·  4μ½”λ©˜νŠΈ  Β·  좜처: pallets/jinja

ν˜„μž¬ map ν•¨μˆ˜λŠ” λ‹€μŒκ³Ό κ°™μ΄λ§Œ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute='path')

의 λ°˜ν™˜κ³Ό ν•¨κ»˜

['/var/file1', '/var/file2']

(λ¬Έμ„œ: http://jinja.pocoo.org/docs/dev/templates/#map)

λ‚˜λŠ” 이것을 ν—ˆμš©ν•˜λŠ” 것을 μ œμ•ˆν•˜κ³  μ‹ΆμŠ΅λ‹ˆλ‹€:

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute=['path', 'mtime'])

λ˜λŠ”

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attributes=['path', 'mtime'])

λ°˜ν™˜ν•΄μ•Ό ν•˜λŠ”

[{'path':'/var/file1', 'mtime': '123'},{'path':'/var/file2', 'mtime': '123'}]

이것이 무엇에 μœ μš©ν•œμ§€ 이미 μ•Œ 수 μžˆμŠ΅λ‹ˆλ‹€. 사전 λͺ©λ‘μ΄ μ œν•œλœ 속성 μ§‘ν•©λ§Œ μœ μ§€ν•˜λ„λ‘ 사전 λͺ©λ‘μ„ μ‘°μž‘ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€.

κ°€μž₯ μœ μš©ν•œ λŒ“κΈ€

λˆ„κ΅°κ°€ μ—¬μ „νžˆ 이것을 ν•„μš”λ‘œ ν•˜λŠ” 경우 λ‹€μŒ μ½”λ“œλ₯Ό μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€( playbooks/filter_plugins/mapattributes.py ).

#!/usr/bin/env python
class FilterModule(object):
  def filters(self):
    return { 'mapattributes': self.mapattributes }

  def mapattributes(self, list_of_dicts, list_of_keys):
    l = []
    for di in list_of_dicts:
      newdi = { }
      for key in list_of_keys:
        newdi[key] = di[key]
      l.append(newdi)
    return l

λ‹€μŒμ„ 톡해 μ‚¬μš©:

ansible_mounts | mapattributes(['mount', 'size_total', 'size_available',])

λͺ¨λ“  4 λŒ“κΈ€

이 κΈ°λŠ₯을 μ’‹μ•„ν•  κ²ƒμž…λ‹ˆλ‹€.

이것이 ν…œν”Œλ¦Ώμ— ν•„μš”ν•œ μ΄μœ κ°€ ν™•μ‹€ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. 사전을 λ°˜λ³΅ν•˜κ³  ν•„μš”ν•œ 속성을 μ‚¬μš©ν•˜λ©΄ λ™μΌν•œ κ²°κ³Όλ₯Ό 얻을 수 μžˆμŠ΅λ‹ˆλ‹€. λ‹€λ₯Έ 데이터가 ν•„μš”ν•œ 경우 λ Œλ”λ§ν•˜κΈ° 전에 Pythonμ—μ„œ ν•΄λ‹Ή μ‘°μž‘μ„ μˆ˜ν–‰ν•˜λŠ” 것이 μ’‹μŠ΅λ‹ˆλ‹€. νŠœν”Œμ„ λ°˜ν™˜ν•˜λŠ” μš©λ„λ₯Ό _μ–΄μ©Œλ©΄_ λ³Ό 수 μžˆμŠ΅λ‹ˆλ‹€.

λˆ„κ΅°κ°€ μ—¬μ „νžˆ 이것을 ν•„μš”λ‘œ ν•˜λŠ” 경우 λ‹€μŒ μ½”λ“œλ₯Ό μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€( playbooks/filter_plugins/mapattributes.py ).

#!/usr/bin/env python
class FilterModule(object):
  def filters(self):
    return { 'mapattributes': self.mapattributes }

  def mapattributes(self, list_of_dicts, list_of_keys):
    l = []
    for di in list_of_dicts:
      newdi = { }
      for key in list_of_keys:
        newdi[key] = di[key]
      l.append(newdi)
    return l

λ‹€μŒμ„ 톡해 μ‚¬μš©:

ansible_mounts | mapattributes(['mount', 'size_total', 'size_available',])

이 λ¬Έμ œκ°€ μ’…λ£Œλ˜κ³  Nee6ione μ†”λ£¨μ…˜μ΄ κ³΅μ‹μ μœΌλ‘œ κ΅¬ν˜„λ˜μ§€ μ•Šμ€ μ΄μœ λŠ” λ¬΄μ—‡μž…λ‹ˆκΉŒ? μΆ”κ°€ ν”ŒλŸ¬κ·ΈμΈ 없이 μ§€μ›λœλ‹€λ©΄ 훨씬 더 간단할 κ²ƒμž…λ‹ˆλ‹€.

이 νŽ˜μ΄μ§€κ°€ 도움이 λ˜μ—ˆλ‚˜μš”?
0 / 5 - 0 λ“±κΈ‰