Ansible run python script

ansible.builtin.script-Запуск локального сценария на удаленном узле после его передачи

Этот модуль является частью ansible-core и включен во все установки Ansible. В большинстве случаев вы можете использовать script короткого имени модуля даже без указания ключевого слова collections: .Однако мы рекомендуем вам использовать FQCN для упрощения ссылки на документацию модуля и во избежание конфликта с другими коллекциями, которые могут иметь такое же имя модуля.

Новинка в версии 0.9:ansible.builtin

Synopsis

  • Модуль script принимает имя сценария, за которым следует список аргументов, разделенных пробелами.
  • Требуется либо команда произвольной формы, либо параметр cmd , см. Примеры.
  • Локальный скрипт по пути будет передан удаленному узлу и затем выполнен.
  • Данный скрипт будет обработан через среду оболочки на удаленном узле.
  • Этот модуль не требует python в удаленной системе, как и модуль ansible.builtin.raw .
  • Этот модуль также поддерживается для целей Windows.

У этого модуля есть соответствующий плагин действия .

Parameters

Notes

  • Обычно предпочтительнее написать Anable модули,чем нажимать на скрипты.Преобразуйте свой скрипт в Допустимый модуль за бонусные очки!
  • ssh соединение плагин заставит выделение псевдо-терминального через -tt , когда выполняются сценарии. Псевдо-тты не имеют канала stderr, и весь stderr отправляется на стандартный вывод. Если вы зависите от разделенных ключей результатов stdout и stderr, переключитесь на набор задач копирования + команд вместо использования скрипта.
  • Если путь к локальному скрипту содержит пробелы,он должен быть процитирован.
  • Этот модуль также поддерживается для целей Windows.
  • Не поддерживает check_mode .
Читайте также:  Благотворительный фонд css конкурс

See Also

Официальная документация по модулю ansible.builtin.shell .

Официальная документация по модулю ansible.windows.win_shell .

Examples

- name: Run a script with arguments (free form) ansible.builtin.script: /some/local/script.sh --some-argument 1234 - name: Run a script with arguments (using 'cmd' parameter) ansible.builtin.script: cmd: /some/local/script.sh --some-argument 1234 - name: Run a script only if file.txt does not exist on the remote node ansible.builtin.script: /some/local/create_file.sh --some-argument 1234 args: creates: /the/created/file.txt - name: Run a script only if file.txt exists on the remote node ansible.builtin.script: /some/local/remove_file.sh --some-argument 1234 args: removes: /the/removed/file.txt - name: Run a script using an executable in a non-system path ansible.builtin.script: /some/local/script args: executable: /some/remote/executable - name: Run a script using an executable in a system path ansible.builtin.script: /some/local/script.py args: executable: python3

Authors

Источник

ansible.builtin.script module – Runs a local script on a remote node after transferring it

This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name script even without specifying the collections: keyword. However, we recommend you use the FQCN for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name.

Synopsis

  • The script module takes the script name followed by a list of space-delimited arguments.
  • Either a free form command or cmd parameter is required, see the examples.
  • The local script at path will be transferred to the remote node and then executed.
  • The given script will be processed through the shell environment on the remote node.
  • This module does not require python on the remote system, much like the ansible.builtin.raw module.
  • This module is also supported for Windows targets.
Читайте также:  Синтаксис стрелочной функции javascript

This module has a corresponding action plugin .

Parameters

Change into this directory on the remote node before running the script.

Path to the local script to run followed by optional arguments.

A filename on the remote node, when it already exists, this step will not be run.

This option controls the autodecryption of source files using vault.

Name or path of a executable to invoke the script with.

Path to the local script file followed by optional arguments.

A filename on the remote node, when it does not exist, this step will not be run.

Attributes

while the script itself is arbitrary and cannot be subject to the check mode semantics it adds creates / removes options as a workaround

Can run in check_mode and return changed status prediction without modifying target

Will return details on what has changed (or possibly needs changing in check_mode), when in diff mode

This action is one of the few that requires no Python on the remote as it passes the command directly into the connection string

Target OS/families that can be operated against

Indicates if an action takes a ‘raw’ or ‘free form’ string as an option and has it’s own special parsing of it

safe_file_operations

Uses Ansible’s strict file operation functions to ensure proper permissions and avoid data corruption

Can automatically decrypt Ansible vaulted files

Notes

  • It is usually preferable to write Ansible modules rather than pushing scripts. Convert your script to an Ansible module for bonus points!
  • The ssh connection plugin will force pseudo-tty allocation via -tt when scripts are executed. Pseudo-ttys do not have a stderr channel and all stderr is sent to stdout. If you depend on separated stdout and stderr result keys, please switch to a copy+command set of tasks instead of using script.
  • If the path to the local script contains spaces, it needs to be quoted.
  • This module is also supported for Windows targets.
  • If the script returns non UTF-8 data, it must be encoded to avoid issues. One option is to pipe the output through base64 .

See Also

Execute shell commands on targets.

Execute shell commands on target hosts.

Examples

- name: Run a script with arguments (free form) ansible.builtin.script: /some/local/script.sh --some-argument 1234 - name: Run a script with arguments (using 'cmd' parameter) ansible.builtin.script: cmd: /some/local/script.sh --some-argument 1234 - name: Run a script only if file.txt does not exist on the remote node ansible.builtin.script: /some/local/create_file.sh --some-argument 1234 args: creates: /the/created/file.txt - name: Run a script only if file.txt exists on the remote node ansible.builtin.script: /some/local/remove_file.sh --some-argument 1234 args: removes: /the/removed/file.txt - name: Run a script using an executable in a non-system path ansible.builtin.script: /some/local/script args: executable: /some/remote/executable - name: Run a script using an executable in a system path ansible.builtin.script: /some/local/script.py args: executable: python3 - name: Run a Powershell script on a windows host script: subdirectories/under/path/with/your/playbook/script.ps1 

Authors

Источник

Ansible playbook to upload and execute a python script

The file upload is working, But execution is failing. Even though I am able to execute the script without any issues directly on the server. Am I doing anything wrong?

I suspect that the mode=755 was the problem here, as the value is interpreted as decimal not octal. Using mode=»0755″ would probably work. The file module documentation covers this but should really have a warning with highlighted text.

2 Answers 2

I have used a similar playbook which works as expected:

# playbook.yml --- - hosts: $ sudo: yes tasks: - name: Copy file copy: src=../files/test.py dest=/opt/test.py owner=howardsandford group=admin mode=755 - name: Execute script command: /opt/test.py 
#!/usr/bin/python # write to a file f = open('/tmp/test_from_python','w') f.write('hi there\n') 
ansible-playbook playbook.yml --extra-vars "target=the_host_to_run_script_on" 
PLAY [the_host_to_run_script_on] *************************************************************** GATHERING FACTS *************************************************************** ok: [the_host_to_run_script_on] TASK: [Copy file] ************************************************************* changed: [the_host_to_run_script_on] TASK: [Execute script] ******************************************************** changed: [the_host_to_run_script_on] PLAY RECAP ******************************************************************** the_host_to_run_script_on : ok=3 changed=2 unreachable=0 failed=0 
$ cat /tmp/test_from_python hi there 

Several differences between our setup:

  • I don’t have single quotes around the copy and command parameters
  • The shebang sets the python interpreter rather than specifying /usr/bin/python from the command line
  • I set the owner of the script to my own username and primary group that is in sudoers, rather than root

Hopefully this can point you in the right direction of where the differences might be.

Источник

Оцените статью