Ansible user create and test ssh connectivity

36 views
Skip to first unread message

Harshal Unhale

unread,
Oct 15, 2020, 1:23:20 PM10/15/20
to Ansible Project
My playbook: 

---
- name: Playbook to create users
  hosts: all
  become: true

  vars_files:
      - /home/devops/become_pass.yml
      - /home/devops/user_secret.yml
  vars:
     - ansible_become_password: "{{ become_pass }}"

  tasks:

     - name: User creation is in progress
       user:
          name: test321
          comment: "Test user"
          password: "{{ user_secret | password_hash('sha512', 'mysecretsalt') }}"
          state: present

     - name: Trying remote connectivity with newly created user
       become: false
       remote_user: test
       vars:
          ansible_ssh_pass: "{{ user_secret }}"

       command:
          cmd: id
       register: x
       no_log: true

     - name: Connectivity result
       debug:
          msg: "User created successfully and remote connectivity with password was successful"
       when: x.rc==0
...

Here I am using vault to pass become password and password to be set for user..

User creation is successful and its picking up password from my encrypted variable..
I have tested connectivity for this user with password.. its successful..

But, I am not able to achieve same from playbook.
I guess - ansible_ssh_pass: "{{ user_secret }}" one is causing issue..
how I can ask playbook to pickup ssh password for user from encrypted variable?

Charles Shaw

unread,
Oct 15, 2020, 9:34:19 PM10/15/20
to Ansible Project
Hi there,

My understanding is that when ansible makes a connection to the remote machine it it'll make the connection as 'ansible_user', and doesn't re-evaluate it for the play. I've split it into two plays, I think it does what you want. Sorry for the formatting :)

Running the playbook with -vvv shows the first play connecting as my default user (ansible) and the second play connects as user boblah.

Ansible 2.9
---
- hosts: linux

  vars_files:
     - ../var_files/user_secret.yml

   tasks:
     - name: Create User
       user:
         name: boblah
         comment: "test user - supersecret pass"
         password: "{{ user_secret | password_hash('sha512', 'mysecretsalt') }}"
         state: present
       become: true

- hosts: linux

  vars_files:
     - ../var_files/user_secret.yml

   vars:
     ansible_user: boblah
     ansible_password: "{{ user_secret }}"

     - name: Test user
       command:
          cmd: id
      register: id

    - name: Connectivity result
      debug:
        msg: "User created successfully and remote connectivity with password was successful"
     when: id.rc==0

First time submitting anything as an answer, hope it helps.

Thanks,
Charles
Reply all
Reply to author
Forward
0 new messages