Ansible: 목록의 각 항목에 새 필드를 채웁니다.

Ansible: 목록의 각 항목에 새 필드를 채웁니다.

저는 Ansible 및 Python 초보자입니다. 목록이 있습니다.

my_items:
- name: item1
  unix_user: unixuser1
  homedir: /home/unixuser2
- name: item2
  unix_user: unixuser2
  homedir: /home/unixuser2

각 "my_items"에 대해 pureftpd 가상 사용자를 생성하고 싶습니다.

역할은 다음과 같은 변수를 기다립니다.

my_items:
- name: item1
  unix_user: unixuser1
  homedir: /home/unixuser2
  uid: 1001
  guid: 1001
- name: item2
  unix_user: unixuser2
  homedir: /home/unixuser2
  uid: 1002
  guid: 1002

나는 (getent를 사용하여) uid/guid를 검색하는 방법을 알고 있습니다. 각 항목에 새 키/값을 추가할 수 있습니다.

- name: "Populate UID and GID in my_items"
  set_fact:
    item: "{{ item | combine( { 'uid': getent_passwd[item.unix_user][1], 'gid': getent_passwd[item.unix_user][2] }) }}"
  with_items: "{{ my_items }}"

그러나 물론 "전역" my_items 변수는 업데이트되지 않습니다.

나는 새로운 "사전"을 만들려고 노력했지만 동시에 너무 많은 개념을 다룰 수는 없습니다.

어떤 도움이라도 주시면 감사하겠습니다!

답변1

나는 마침내 그것을 성공시킬 수 있었다.

- name: "getent variables"
  getent:
    database: passwd
    
- name: Create Dictionary for FTP accounts
  set_fact:
    ftp_accounts: >
       {{ ftp_accounts | default([]) + [{
           'name': item.unix_user,
           'password': item.ftp_password,
           'homedir': item.path,
           'uid': getent_passwd[item.unix_user][1],
           'guid': getent_passwd[item.unix_user][2]
          } ] }}
  with_items:
    "{{ my_items }}"

그런 다음 내 역할에 새로운 사전을 보낼 수 있습니다.

- name: gcoop-libre.pure-ftpd
  vars:
    pureftpd_virtual_users: "{{ ftp_accounts }}"

조심하세요. 저는 localhost에서 작업하고 있었지만 Unix 사용자는 (분명히) 원격에서만 생성되었으므로 getent_passwd[item.unix_user]가 정의되지 않아 암호 같은 오류 메시지가 표시됩니다(유니코드로 강제 변환: 문자열 또는 버퍼 필요, 목록 발견됨) ).

관련 정보