You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible角色为用户自动生成随机密码失败问题求助

问题分析
  1. 多行字符串标记错误:第一个set_fact使用|将结果转为字符串而非字典列表格式,后续变量解析时直接丢失了u_pass字段。
  2. 嵌套Jinja语法错误:在combine的字典中,{{ lookup(...) }}属于嵌套双大括号,Jinja会将其当作纯字符串处理,不会执行密码生成逻辑。
  3. 冗余任务无效:第二个set_fact完全多余,反而会触发变量的异常解析。
修正后的完整代码
---
# 为每个用户生成随机密码并合并到用户字典,同时转为Linux系统可用的加密哈希
- set_fact:
    user_details: "{{ user_details | map('combine', { 'u_pass': lookup('password', '/dev/null chars=ascii_letters,digits length=15') | password_hash('sha512') }) | list }}"

- debug:
    msg: "{{ item.name }} 的加密密码: {{ item.u_pass }}"
  loop: "{{ user_details }}"
  loop_control:
    label: "{{ item.name }}"

- block:
   - name: 管理用户组
     group:
        name: "{{ item.name }}"
        gid: "{{ item.gid }}"
        state: present
     loop: "{{ group_details }}"
     loop_control:
       label: "{{ item.name }}"

   - name: 管理用户 [创建账号]
     user:
       name: "{{ item.name }}"
       comment: "{{ item.comment }}"
       uid: "{{ item.uid }}"
       shell: "{{ item.shell | default('/bin/bash') }}"
       groups: "{{ item.groups }}"
       append: yes
       password: "{{ item.u_pass }}"
       state: "{{ action }}"
     loop: "{{ user_details }}"
     loop_control:
       label: "{{ item.name }}"
关键修正点说明
  • 移除多行字符串标记:直接通过Jinja表达式处理user_details,保持其字典列表的原生类型,确保后续遍历和字段访问正常。
  • 修正密码生成逻辑:去掉嵌套的{{ }},直接执行lookup('password', ...)生成随机明文密码,再通过password_hash('sha512')转为Linux系统认可的加密哈希值(否则用户无法用生成的密码登录)。
  • 移除冗余任务:第一个set_fact已完成变量更新,无需重复赋值。
  • 显式转为列表:map返回的是迭代器,用| list转为列表确保loop能正常遍历。
额外提示(可选)

如果需要记录明文密码,可调整逻辑先保存明文再生成加密哈希:

# 先生成明文密码
- set_fact:
    user_details_with_plain: "{{ user_details | map('combine', { 'plain_pass': lookup('password', '/dev/null chars=ascii_letters,digits length=15') }) | list }}"

# 基于明文生成加密哈希并合并
- set_fact:
    user_details: "{{ user_details_with_plain | map('combine', { 'u_pass': item.plain_pass | password_hash('sha512') }) | list }}"
  loop: "{{ user_details_with_plain }}"
  loop_control:
    label: "{{ item.name }}"

# 将明文密码保存到控制节点本地文件
- name: 保存明文密码到本地
  copy:
    content: |
      {% for user in user_details_with_plain %}
      {{ user.name }}: {{ user.plain_pass }}
      {% endfor %}
    dest: /tmp/user_plain_passwords.txt
    mode: '0600'
  delegate_to: localhost

内容的提问来源于stack exchange,提问作者johnny bravo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:58:09