Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible password_hash with variable

Tags:

ansible

I am writing a simple task to create a user. As part of this task, I want to read the password from defaults/main.yml

defaults/main.yml

test_user: testuser
test_group: testgroup
test_user_password: somepassword

my tasks file is as below

- 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/ksh
    group: "{{ test_group }}"
    update_password: on_create

This gives me a unexpected templating error. How can I read the password from main.yml and use it inside the password filter?

like image 695
Anand Rao Avatar asked Dec 18 '22 06:12

Anand Rao


1 Answers

In the Creating testuser task remove the square brackets around test_user_password. When a variable is referenced in Ansible it has to be enclosed with {{}}.

- 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
like image 60
tux Avatar answered Jan 09 '23 11:01

tux