在ansible中为linux用户设置密码

时间:2018-04-06 00:28:42

标签: ansible

尝试使用模块user管理用户密码时,我每次执行playbook时都会收到密码更改通知,并且此行为不依赖于ansible版本(在所有主要版本2.0 - 2.5上测试),目标分布(在稳定的CentOS,Debian和Ubuntu上测试)或update_password选项。

- name: This is in vault in real playbook of course
  set_fact:
    testuser_password : '123456'

- name: Manage test user
  user:
    name: testuser
    uid: 1001
    state: present
    password: "{{ testuser_password |password_hash('sha512')}}"

名为“管理测试用户”的任务始终标记为已更改。为了避免我使用这种奇怪的结构

- name: This is in vault in real playbook of course
  set_fact:
    testuser_password : '123456'

- name: Check if user exists
  shell: "getent shadow testuser | awk -F: '{ print $2}'"
  changed_when: false
  check_mode: false
  register: userexists

- name: Get salt for existing password
  shell: "getent shadow testuser | awk -F$ '{ print $3}'"
  changed_when: false
  check_mode: false
  register: passwordsalt
  when: userexists.stdout != ""

- name: Encrypt local password with salt
  set_fact:
    localsaltedpass: "{{ testuser_password |password_hash('sha512', passwordsalt.stdout )}}"
  when: userexists.stdout != ""

- name: Update remote password
  user:
    name: "testuser"
    uid: 1001
    password: "{{ testuser_password |password_hash('sha512')}}"
  when: 
    - userexists.stdout != ""
    - userexists.stdout != localsaltedpass

- name: Create test user if it does not exist
  user:
    name: "testuser"
    uid: 1001
    state: present
    password: "{{ testuser_password |password_hash('sha512')}}"
  when: userexists.stdout == ""

虽然这种方法解决了这个问题但对我来说看起来不太好。有没有想法如何正确地管理用户密码?

2 个答案:

答案 0 :(得分:1)

请注意像下划线这样的特殊字符会导致:{"msg": "crypt.crypt 不支持 'sha512_crypt' 算法"} 所以现在,你的盐中没有下划线或其他特殊字符!!!

https://github.com/ansible/ansible/issues/71107 提及:

password_hash 可用的所有散列方案仅支持 [./0-9A-Za-z] 描述的正则表达式范围内的字符

除此之外,盐长要求不同:

md5:0-8 个字符 bcrypt:22 个字符 sha256:0-16 个字符 sha512:0-16 个字符

答案 1 :(得分:0)

要设置密码幂等,需要在salt_hash函数中添加salt作为第二个参数,如下所示:

- name: This should be in a vault in real playbook of course
  set_fact:
    user_password: 'passw0rd'
    user_salt: 'some_salt'

- name: Creating testuser
  user:
   name: "username"
   password: "{{ user_password | password_hash('sha512', user_salt) }}"
   state: present
   shell: /bin/bash
   update_password: on_create

非常感谢@ {3}}推进正确的方向。