在ansible中为linux用户设置幂等密码

miw*_*iwa 4 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')}}"
Run Code Online (Sandbox Code Playgroud)

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

- 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 == ""
Run Code Online (Sandbox Code Playgroud)

虽然这种方法解决了问题,但对我来说看起来不太好。有什么想法如何以正确的方式幂等地管理用户密码?

miw*_*iwa 7

发生这种情况是因为每次调用password_hash过滤器时盐都会随机再生。为了使设置密码幂等,我们必须保留 salt 并将其添加为第二个参数,如下所示:

- name: This should be stored in a vault in a real playbook of course
  set_fact:
    user_password: 'passw0rd'
    user_salt: 'some.salty.salt'

- name: Manage testuser
  user:
   name: "username"
   password: "{{ user_password | password_hash('sha512', user_salt) }}"
   state: present
   shell: /bin/bash
   update_password: on_create
Run Code Online (Sandbox Code Playgroud)

非常感谢@ konstantin-suvorov推动了正确的方向。

另外,请记住,salt 中只能使用字母数字、点和斜线,并且对于 sha512,它的长度不应超过 16 个字符。感谢@Peter De Zwart 的澄清。