如何使用 Ansible 的 user 模块更改 Linux 用户的主组?以下是一个示例,展示如何通过 Ansible Playbook 更改用户的主组。
Ansible 模块 user 概述
模块名称:ansible.builtin.user
功能:管理用户账户
ansible.builtin.user 是 Ansible 核心模块的一部分,用于管理用户账户。
该模块非常稳定,已经存在多年,支持多种 Linux 发行版、SunOS、macOS 和 FreeBSD。
对于 Windows 系统,建议使用 ansible.windows.win_user 模块。
参数介绍
name(字符串):用户名,唯一必需参数。group(字符串):用户的主组,用户必须属于一个主组。groups(列表):用户将被添加到的附加组列表。这些组有时也被称为“次要”、“附加”或“补充”组。append(布尔值):no/yes。如果设置为yes,用户将被添加到指定的组中。如果设置为no,用户的组成员资格将被指定的组覆盖。 注意:如果设置为no,用户之前的组关联将丢失,请谨慎使用!
示例:使用 Ansible Playbook 更改用户的主组
Playbook 文件:user_group_changeprimary.yml
---
- name: user module demo
hosts: all
become: true
vars:
myuser: "example" # 用户名
mygroup: "users" # 新的主组
tasks:
- name: 更改主组
ansible.builtin.user:
name: "{{ myuser }}"
group: "{{ mygroup }}"
执行命令
$ ansible-playbook -i virtualmachines/demo/inventory users_and_groups/user_group_changeprimary.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
执行前后对比
执行前:
$ ssh devops@demo.example.com
[devops@demo ~]$ sudo su
[root@demo devops]# cat /etc/os-release
NAME="Red Hat Enterprise Linux"
VERSION="8.5 (Ootpa)"
ID="rhel"
ID_LIKE="fedora"
VERSION_ID="8.5"
PLATFORM_ID="platform:el8"
PRETTY_NAME="Red Hat Enterprise Linux 8.5 (Ootpa)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:8::baseos"
HOME_URL="https://www.redhat.com/"
DOCUMENTATION_URL="https://access.redhat.com/documentation/red_hat_enterprise_linux/8/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"
REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 8"
REDHAT_BUGZILLA_PRODUCT_VERSION=8.5
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="8.5"
[root@demo devops]# getent passwd | grep example
example:x:1002:1002:Ansible example:/home/example:/bin/bash
[root@demo devops]# id example
uid=1002(example) gid=1002(example) groups=1002(example),10(wheel)
[root@demo devops]# groups example
example : example wheel
[root@demo devops]#
执行后:
$ ssh devops@demo.example.com
[devops@demo ~]$ sudo su
[root@demo devops]# getent passwd | grep example
example:x:1002:100:Ansible example:/home/example:/bin/bash
[root@demo devops]# id example
uid=1002(example) gid=100(users) groups=100(users),10(wheel)
[root@demo devops]# groups example
example : users wheel
[root@demo devops]#
注意事项
- 主组和附加组:
group参数设置用户的主组,而groups参数设置附加组。 append参数:如果需要保留用户现有的附加组,可以使用append: yes。如果需要完全覆盖,可以使用append: no。- 权限:更改用户组需要
root权限,因此需要使用become: true。 - 幂等性:如果用户的主组未发生变化,任务将不会重复执行,确保 Playbook 的幂等性。
希望这个示例对您有帮助!