windowspowershellansiblesessionid

Request Windows Session ID via Ansible


here is what I want to achieve:

I have a Linux machine which is using Ansible to start a process on a remote Windows machine. I know for actually seeing the process starting on the windows machine I need to use the active session ID from the Windows machine. There are different ways to get this session ID, e.g. type in "qwinsta" in command line. Problem is, this ID changes on new start up, so I need a variable in my Ansible Playbook which automatically changes after a request to the Windows machine which delivers the needed session ID. I hope you understand what I mean? Is there a powershell command or another solution which can be put in an Ansible playbook so that I have a variable which just contains the number of the needed session?

e.g. in the attached picture my variable session_id = 4 so in my ansible playbook I could use win_shell with PsExec.exe -i 4 and I want to replace the 4 with some kind of dynamic variable.

session

If you need further information, please ask.


Solution

  • I solved this problem with:

    - name: Get Session ID with cmd command
      win_shell: for /f "tokens=2-4" %a in ('query session %username%') do @if "%c"=="Active" echo %b
      args:
        executable: cmd
      register: session_id
    

    Next step I used:

    session: '{{ session_id.stdout }}'