如何使用 Ansible 的 user 模块在 Linux 上设置用户的密码过期时间?以下是一个示例,展示如何通过 Ansible Playbook 设置用户密码的过期时间。

Ansible 模块 user 概述

模块名称:ansible.builtin.user 功能:管理用户账户 ansible.builtin.user 是 Ansible 核心模块的一部分,用于管理用户账户。 该模块非常稳定,已经存在多年,支持多种 Linux 发行版、SunOS、macOS 和 FreeBSD。 对于 Windows 系统,建议使用 ansible.windows.win_user 模块。

参数介绍

  • name(字符串):用户名,唯一必需参数。
  • password_expire_min(整数):密码最小有效天数(Linux 的 -m 参数)。
  • password_expire_max(整数):密码最大有效天数(Linux 的 -M 参数)。

这些参数仅在 Linux 系统上有效,用于设置密码过期策略。

  • password_expire_min:设置密码更改后的最小天数,在此期间用户不能再次更改密码。
  • password_expire_max:设置密码的最大有效天数,超过此天数后用户必须更改密码。
  • 设置为 99999 可以禁用密码老化策略。

示例:使用 Ansible Playbook 设置用户密码过期时间

Playbook 文件:user_password_expiration.yml
---
- name: user module demo
  hosts: all
  become: true
  vars:
    myuser: "example"  # 要设置密码过期时间的用户名
  tasks:
    - name: 设置密码过期时间
      ansible.builtin.user:
        name: "{{ myuser }}"
        password_expire_min: 7  # 最小有效天数
        password_expire_max: 90  # 最大有效天数

执行命令

$ ansible-playbook -i demo/inventory user_password_expiration.yml

执行结果

PLAY [user module demo] ***************************************************
TASK [Gathering Facts] *****************************************************
ok: [demo.example.com]
TASK [设置密码过期时间] ******************************************************
changed: [demo.example.com]
PLAY RECAP *****************************************************************
demo.example.com           : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

验证密码过期时间

可以通过 chage 命令验证密码过期时间是否已正确设置:

$ ssh devops@demo.example.com
$ sudo su -
[root@demo ~]# chage -l example
Last password change     : Nov 08, 2021
Password expires     : Feb 06, 2022
Password inactive     : never
Account expires      : never
Minimum number of days between password change  : 7
Maximum number of days between password change  : 90
Number of days of warning before password expires : 7
  • Password expires:显示密码过期日期。
  • Minimum number of days between password change:显示密码最小有效天数。
  • Maximum number of days between password change:显示密码最大有效天数。

注意事项

  1. 密码过期策略:password_expire_min 和 password_expire_max 参数仅在 Linux 系统上有效。
  2. 禁用密码老化:将 password_expire_max 设置为 99999 可以禁用密码老化策略。
  3. 权限:设置密码过期时间需要 root 权限,因此需要使用 become: true。
  4. 幂等性:如果密码过期策略未发生变化,任务将不会重复执行,确保 Playbook 的幂等性。

希望这个示例对您有帮助!