Press "Enter" to skip to content

Ansible添加用户

本文演示了Ansible批量添加用户zhang3,并将用户的密码设定为12345678的过程。

方法一

$ pip install passlib

#获得采用sha512加密以后的密码串
$ python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('12345678')"
$6$rounds=656000$SJkYJamGImQ/OVZC$.9RslNw5vUhd5bBCO3EkHCl/k0eVDlyRhXPXKUooF4nSQNoFdQw1STHj7WlYnOefXmb4IOZDuL49zYEDmSAHM/

$ vim useradd.yml    #写入如下内容
- hosts: 192.168.34.73
  vars:
    user: zhang3
    #run the command like below to generate crypted passwords.
    #generate crypted passwords: python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('12345678')"
    password: '$6$rounds=656000$SJkYJamGImQ/OVZC$.9RslNw5vUhd5bBCO3EkHCl/k0eVDlyRhXPXKUooF4nSQNoFdQw1STHj7WlYnOefXmb4IOZDuL49zYEDmSAHM/'
  tasks:
  - name: create new user locadm
    user: name={{ user }} shell=/bin/bash group=ndsdevelop groups=sudo password={{ password }} update_password=always append=yes

group表示把用户加入某组,groups表示附属组,update_password表示每次都更新密码(除了可以设定为always以外,还可以设置成on_create表示只为新用户修改密码),append=yes表示是新添加的用户
如果是为已有用户修改密码,去掉append=yes即可。
然后运行之

$ ansible-playbook useradd.yml

方法二

$ vim useradd.yml    #写入如下内容
- hosts: 192.168.34.73
  vars:
    user: zhang3
  tasks:
  - name: create new user {{ user }}
    user: name={{ user }} shell=/bin/bash group=ndsdevelop password={{ '12345678' |password_hash('sha512') }} update_password=always append=yes

然后运行之

$ ansible-playbook useradd.yml

写法三(推荐写法,灵活,可带参数)

$ vim useradd.yml    #写入如下内容
- hosts: "{{ host }}"
  vars:
    UserName: "{{ user }}"
    ThePassword: "{{ new_pass }}"
  tasks:
  - name: create new user {{ UserName }}
    user: name={{ UserName }} shell=/bin/bash group=ndsdevelop groups=sudo password={{ ThePassword |password_hash('sha512') }} update_password=always append=yes

然后运行之

$ ansible-playbook useradd.yml -e "host=192.168.15.195 user=zhang3 new_pass=12345678"

在上例中,new_pass是密码,如果new_pass里有特殊的字符,或者new_pass是一串数组的话,它将被转义。若不想被转义,可以使用如下方法

$ cat user.json 
host: other
user: locadmin
new_pass: 'Fxx6unM$R%I$Jna&'

$ ansible-playbook useradd.yml -e "@user.json"    #使用JSON格式的文件即可

删除用户

$ ansible 192.168.34.73 -m user -a 'name=zhang3 state=absent remove=yes'

参考文档:
How do I generate crypted passwords for the user module?
ANSIBLE – user – Manage user accounts
ansible使用2-命令
Creating a new user and password with Ansible
ANSIBLE – Variables

Leave a Reply

Your email address will not be published. Required fields are marked *