Skip to content

Instantly share code, notes, and snippets.

Created August 24, 2023 23:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Setting Samba passwords with Ansible

Scenario: You want to create a user in Linux, and set a Samba password for it, all from Ansible:


  • This will not update the Samba password if you change the variable.

To create the encrypted vault string, run: ansible-vault encrypt_string --ask-vault-password 'some_password'

- name: Create OS group
    name: smbgroup
    state: present
    system: no

- name: Create OS user
    name: smbuser
    group: smbgroup
    createhome: no
    system: no
    state: present
    shell: /sbin/nologin

- name: Fetch current smbpasswd users
  command: /usr/bin/pdbedit -L
  register: pdb_users

- name: Set Samba password for smbuser
  shell: echo '{{ smbuser_password }}' | /usr/bin/smbpasswd -s -a smbuser
  when: pdb_users.stdout.find('smbuser') == -1
    smbuser_password: !vault |
Copy link

larsks commented Aug 25, 2023

You don't need a shell command with an echo statement here. You can use a command task with the stdin directive:

- name: Set Samba password for smbuser
    cmd: /usr/bin/smbpasswd -s -a smbuser
    stdin: |
      {{ smbuser_password }}
      {{ smbuser_password }}
  when: pdb_users.stdout.find('smbuser') == -1
    smbuser_password: secret

Note that we need to provide the password twice, because smbpasswd wants both the password and a confirmation.

Copy link

cmsj commented Aug 25, 2023

Ooh yes, that's definitely nicer! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment