【问题标题】:Ansible password_hash with variable带变量的 Ansible 密码哈希
【发布时间】:2023-03-31 08:26:01
【问题描述】:

我正在编写一个简单的任务来创建用户。作为此任务的一部分,我想从 defaults/main.yml 读取密码

defaults/main.yml

test_user: 测试用户
test_group: 测试组
test_user_password: 一些密码

我的任务文件如下
- 名称:“为 testuser 创建组”
组:
名称:“{{ test_group }}”
状态:目前

- 名称:“创建测试用户”
用户:
名称:“{{ test_user }}”
密码:“{{ [test_user_password] | password_hash('sha512') }}”
外壳:/bin/ksh
组:“{{ test_group }}”
更新密码:on_create

这给了我一个意外的模板错误。如何从 main.yml 读取密码并在密码过滤器中使用?

【问题讨论】:

    标签: ansible


    【解决方案1】:

    在创建 testuser 任务中,删除 test_user_password 周围的方括号。在 Ansible 中引用变量时,必须用 {{}} 括起来。

    - hosts: localhost
      remote_user: user
      become: yes
    
      vars:
        test_user: testuser
        test_group: testgroup
        test_user_password: somepassword
    
      tasks:
        - name: Creating Group for testuser
          group:
             name: "{{ test_group }}"
             state: present
    
        - name: Creating testuser
          user:
             name: "{{ test_user }}"
             password: "{{ test_user_password | password_hash('sha512') }}"
             shell: /bin/bash
             group: "{{ test_group }}"
             update_password: on_create
    

    【讨论】:

    • 如何在角色中使用变量而不是test_user_passwordpassword: "{{ '{{test_user_password}}' | password_hash('sha512') }}" 这对我不起作用,但我在某个地方找到了它应该起作用的地方...
    • test_user_password 已经是一个变量。在上面的答案中,它设置为 somepassword
    【解决方案2】:

    考虑到给定任务将始终被标记为“已更改”,这意味着它不是幂等的。为避免这种行为,您可以将 salt 作为第二个参数添加到 password_hash 函数,如下所示:

    - name: Creating testuser
      user:
         name: "{{ test_user }}"
         password: "{{ test_user_password | password_hash('sha512', test_user_salt) }}"
         shell: /bin/bash
         group: "{{ test_group }}"
         update_password: on_create
    

    【讨论】:

      猜你喜欢
      • 2016-05-23
      • 1970-01-01
      • 2013-04-13
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多