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

Ansible跨主机组使用变量报错:plain_pwd未定义,如何解决?

解决Ansible跨主机组传递变量的问题

问题根源

你通过set_fact生成的plain_pwd是web_{{ env }}组主机的专属主机变量,Ansible默认不会在不同主机组间共享这类变量,所以切换到db_{{ env }}组后会提示变量未定义。

具体解决方法

方法一:将变量存储到localhost(推荐)

修改gen_pwd.yml的set_fact任务,把变量绑定到localhost的主机变量上,所有后续主机组都能通过hostvars访问:

- name: Generate random password without special characters
  become: yes
  become_user: xyz
  command: "mkpasswd -l 6 -d 1 -c 1 -C 1 -s 0"
  register: _new_pwd
  run_once: true
  #no_log: true  # 建议开启,避免密码泄露到日志

- name: Store password to localhost variable
  set_fact:
    plain_pwd: "{{ _new_pwd.stdout }}"
  delegate_to: localhost
  run_once: true

修改print_pwd.yml,从localhost的hostvars中读取变量:

- name: Print password in scoring
  debug:
    msg: "{{ hostvars['localhost'].plain_pwd }}"

方法二:直接给db组主机注入变量

用add_host模块把生成的密码直接赋值给db_{{ env }}组的所有主机,无需修改print_pwd.yml:
在gen_pwd.yml的set_fact之后添加任务:

- name: Inject password to all db hosts
  add_host:
    name: "{{ item }}"
    plain_pwd: "{{ _new_pwd.stdout }}"
  loop: "{{ groups['db_' ~ env] }}"
  run_once: true

此时print_pwd.yml保持原样即可正常访问plain_pwd。

方法三:通过本地文件传递(适合复杂场景)

先把密码写入本地文件,再让db组读取文件内容:
修改gen_pwd.yml,添加写入文件的任务:

- name: Save password to local file
  copy:
    content: "{{ _new_pwd.stdout }}"
    dest: /tmp/ansible_db_pwd.txt
    mode: '0600'  # 限制文件权限,避免泄露
  delegate_to: localhost
  run_once: true

修改print_pwd.yml读取文件:

- name: Read password from local file
  slurp:
    src: /tmp/ansible_db_pwd.txt
  delegate_to: localhost
  register: _pwd_content

- name: Print password in scoring
  debug:
    msg: "{{ _pwd_content.content | b64decode }}"

注意事项

  • 密码属于敏感数据,建议给生成和输出密码的任务加上no_log: true,防止密码被记录到Ansible日志中。
  • 方法一和方法二无需额外依赖,是最简洁的跨组变量传递方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:45:43