ansible批量更新密码
2025-02-25 / shell / 51 次围观 / 0 次吐槽 /playbook_PW:
Markup
- name: 更新密码
hosts: all
gather_facts: no
vars_files:
- host.yml
tasks:
- name: 修改Root密码
ansible.builtin.shell: |
echo 'root:{{ new_root_password }}' | chpasswd
args:
executable: /bin/bash
become: yes
become_method: su
become_user: root
become_flags: '-s /bin/sh' # 指定 Shell 环境
vars:
ansible_become_password: "{{ root_password }}" # 原 root 密码
# no_log: true
register: passwd_result
changed_when: passwd_result.rc == 0
failed_when:
- "'Authentication token manipulation error' in passwd_result.stderr"
- passwd_result.rc != 0
- name: 验证新密码有效性
ansible.builtin.shell: |
echo "{{ new_root_password }}" | su -c "id -u" root
become: yes
become_method: su
become_user: weihu
vars:
ansible_become_password: "{{ new_root_password }}"
register: auth_check
failed_when: auth_check.rc != 0
# no_log: true
- name: 显示结果
ansible.builtin.debug:
msg: "Root 密码已在 {{ inventory_hostname }} 更新"
when: passwd_result.changed
generate_host_yml.sh:用于生成host.yml
Bash
#!/bin/bash
# 检查是否提供了输入文件
if [ -z "$1" ]; then
echo "请提供包含主机信息的文本文件(例如 hosts.txt)。"
exit 1
fi
# 输出文件
OUTPUT_FILE="host.yml"
# 写入 YAML 文件头部
echo "all:" > "$OUTPUT_FILE"
echo " hosts:" >> "$OUTPUT_FILE"
# 读取输入文件并转换为 YAML 格式
while IFS=' ' read -r ip root_pass weihu_pass new_root_pass; do
if [ -n "$ip" ] && [ -n "$root_pass" ] && [ -n "$weihu_pass" ] && [ -n "$new_root_pass" ]; then
# 写入每个主机的 YAML 格式
echo " server_${ip}:" >> "$OUTPUT_FILE"
echo " ansible_host: $ip" >> "$OUTPUT_FILE"
echo " ansible_user: weihu" >> "$OUTPUT_FILE"
echo " ansible_ssh_pass: \"$weihu_pass\"" >> "$OUTPUT_FILE"
echo " root_password: \"$root_pass\"" >> "$OUTPUT_FILE"
echo " new_root_password: \"$new_root_pass\"" >> "$OUTPUT_FILE"
else
echo "警告:跳过无效行 - $ip $root_pass $weihu_pass $new_root_pass"
fi
done < "$1"
echo "host.yml 文件已生成。"
执行命令:
Bash
ansible-playbook playbook_PW.yml -i host.yml
- 上一篇:tar解压指定后缀文件并(不保留路径)
- 下一篇:
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.