1

I'm using ansible to manage several windows hosts on the cloud, I need to create a log file and link it to another file, so I use the follow playbook

- name: init the directory structure of windows
  hosts: '{{windows_hosts}}'
  tasks:
   - name: create log file and link it to log directory
     win_command: mklink log D:\prod\log
     args:
        chdir: D:\prod\project

when running this playbook, the hosts can be found successfully, but I got the following error report

> TASK [Gathering Facts]
> ********* ok: [111.111.2.40]
> 
> TASK [create log file and link it to log directory]
> ********* fatal: [111.231.76.40]: FAILED! => {"changed": false, "cmd": "mklink log
> D:\\prod\\log", "msg": "Exception calling \"SearchPath\" with \"1\"
> argument(s): \"Could not locate the following executable
> mklink.exe\"", "rc": 2}

and I tryed this command on the remote host in the same directory, it can be execute successfully. I don't know what to do......

Julia Chen
  • 43
  • 2
  • 7

2 Answers2

5

win_command is for running executables directly. Hence the user's environment isn't applied and you aren't running inside a dos box or powershell window

so 'mklink' isn't actually an executable - its a built-in feature of the cmd.exe program. So to run mklink via win_command, you'd have to run the cmd.exe program and pass it an argument to tell it do what 'mklink' does, like this:

win_command: cmd.exe /k mklink log D:\prod\log

  • Thank you! You answer perfectly solved my problem! but I don't understand the function of "/k", I tried to omit it, there was no error, but the no softlink is generated! – Julia Chen Jul 13 '18 at 03:20
  • And can you help me on another similar problem? thank you very much!!! https://stackoverflow.com/questions/51317443/ansible-win-copy-does-not-work-error-src-file-does-not-exist – Julia Chen Jul 13 '18 at 03:59
  • 1
    you can take a look at cmd.exe /? for all the options. – Random_Automation Jul 13 '18 at 08:09
  • @JuliaChen below is some of the manual --- Starts a new instance of the Windows command interpreter CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] [[/S] [/C | /K] string] /C Carries out the command specified by string and then terminates /K Carries out the command specified by string but remains /S Modifies the treatment of string after /C or /K (see below) /Q Turns echo off /D Disable execution of AutoRun commands from registry (see below) --- ... this is the max I am allowed to post. More options under "cmd.exe /?" – D1v3 May 31 '20 at 12:28
2

Do the following way:

---
  - name: Run Windows Command
    hosts: windows
    gather_facts: False

    tasks: 
      - name: win command
        win_shell: cmd /k mklink log D:\prod\log
        args: 
          chdir: D:\prod\project
imjoseangel
  • 3,543
  • 3
  • 22
  • 30