【问题标题】:Setting password idempotently for linux user in ansible在ansible中为linux用户幂等设置密码
【发布时间】:2021-01-17 20:11:35
【问题描述】:

在尝试使用模块 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 == ""

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

【问题讨论】:

  • 为什么不在你的剧本/保险库中储存盐?
  • 你真是个天才!非常感谢您朝着正确的方向前进。能否请您回答问题,以便我将您的答案标记为正确答案?
  • @techraf 删除了具有相同想法的答案。我会将其标记为取消删除。

标签: ansible


【解决方案1】:

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

- 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

非常感谢@konstantin-suvorov 朝着正确的方向前进。

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-31
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多