Home > Net >  Using "become: true" to change default shell with Ansible not working
Using "become: true" to change default shell with Ansible not working

Time:05-21

Using become to change the default shell for a user is not giving the intended result. Using:

- name: Change default shell to zsh
  shell: sudo chsh -s $(which zsh) $(whoami)

/etc/passwd looks like:

root:x:0:0:root:/root:/bin/bash
ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/usr/bin/zsh

Which is the intended result, i.e., changing the default shell for the ubuntu user to zsh. Now, I'd rather use become:

- name: Change default shell to zsh
  become: true
  shell: chsh -s $(which zsh)

But then /etc/passwd looks like:

root:x:0:0:root:/root:/usr/bin/zsh
ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash

Notice that zsh was set for root only.

What am I missing here? Isn't become: true plus shell: chsh -s $(which zsh) the same as sudo chsh -s $(which zsh) $(whoami) or sudo chsh -s $(which zsh)?

If I add $(whoami) like:

- name: Change default shell to zsh
  become: true
  shell: chsh -s $(which zsh) $(whoami)

I get the same, root with zsh but not the user I want to change.

CodePudding user response:

I'd use something like this:

- name: Ensure the user 'ubuntu' has a zsh shell.
  user:
    name: ubuntu
    shell: /bin/zsh
    state: present
  become: yes

CodePudding user response:

This worked:

- name: Register current user (workaround to change default shell)
  shell: whoami
  register: current_user

- name: Change default shell to zsh
  become: true
  shell: "chsh -s $(which zsh) {{ current_user.stdout }}"

See the comments above for the details. In short, I had to run whoami first so that the right user was used when running chsh.

  • Related