我有一个 Linux 用户,他的主目录中有各种文件夹和文件:
User: foo
/home/foo/somefolder
我想重命名该用户并移动他们的主目录,最终得到:
User: bar
/home/bar/somefolder
我会手工做这个
sudo usermod --login new_username old_username
其次是
sudo usermod --home /home/new_username --move-home new_username
我可以创建一个 Ansible 角色来帮我做这件事吗?
在 Ansible 中用户模块我可以找到:
home Optionally set the user's home directory.
move_home If set to yes when used with home=, attempt to move the user's old home directory to the specified directory if it isn't there already and the old home exists.
这听起来像是有意修改,但如何指定重命名本身?
答案1
当我必须自己在一些系统上重命名用户时,我想出了一个快速的 ansible 剧本。剧本执行以下操作:
- 为 root 用户添加 ssh 密钥(作为旧用户)
- 修改 sshd 以便 root 可以登录(作为旧用户)
- 终止用户(以 root 身份)正在运行的所有进程
- 移动主目录(以 root 身份)
- 重命名用户(作为 root)
- 恢复旧的 sshd 配置(以 root 身份)
有三个变量需要设置,一个用于旧用户名,一个用于新用户名,一个用于添加到 root 的 ssh 密钥。
---
- name: "Rename user"
hosts: all
become: true
gather_facts: no
ignore_errors: true
vars:
ssh_key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_ed25519.pub') }}"
old_username: john
new_username: johnny
handlers:
- name: restart sshd
service:
name: ssh
state: restarted
tasks:
- name: Install ssh key for root access
authorized_key:
user: root
key: "{{ ssh_key }}"
state: present
remote_user: "{{ old_username }}"
- name: Make sure root can ssh in
lineinfile:
dest: /etc/ssh/sshd_config
backup: yes
regexp: "^PermitRootLogin"
line: "PermitRootLogin prohibit-password"
state: present
remote_user: "{{ old_username }}"
register: sshd_config
notify: restart sshd
- name: Kill processes by user
shell: "pkill -u {{ old_username }}"
remote_user: root
ignore_errors: true
- name: Move home directory
user:
name: "{{ old_username }}"
home: "/home/{{ new_username }}"
move_home: yes
remote_user: root
- name: Rename user
command: "usermod --login {{ new_username }} {{ old_username }}"
remote_user: root
ignore_errors: true
- name: Restore sshd config
copy:
remote_src: yes
src: "{{ sshd_config.backup }}"
dest: /etc/ssh/sshd_config
remote_user: root
notify: restart sshd