Ansible raw install python

ansible.builtin.raw-Выполняет низкую и грязную команду

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

Synopsis

  • Выполняет низкоуровневую и грязную команду SSH,не проходя через модульную подсистему.
  • Это полезно и должно выполняться только в некоторых случаях. Распространенный случай — установка python в системе без установленного по умолчанию python. Другой говорит с любыми устройствами, такими как маршрутизаторы, на которых не установлен Python. В любом другом случае гораздо более целесообразно использовать модуль ansible.builtin.shell или ansible.builtin.command .
  • Аргументы, переданные raw , запускаются напрямую через настроенную удаленную оболочку.
  • Стандартный вывод,вывод ошибки и код возврата возвращаются,когда они доступны.
  • Для этого модуля нет поддержки обработчика изменений.
  • Этот модуль не требует python в удаленной системе, как и модуль ansible.builtin.script .
  • Этот модуль также поддерживается для целей Windows.

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

Parameters

Измените оболочку,используемую для выполнения команды.Должен быть абсолютный путь к исполняемому файлу.

При использовании повышения привилегий ( become ) оболочка по умолчанию будет назначена, если она не предоставлена, поскольку повышение привилегий требует оболочки.

Читайте также:  Даны три целых числа определите сколько среди них совпадающих python

Notes

  • Если вы используете raw из playbook, вам может потребоваться отключить сбор фактов с помощью gather_facts: no , если вы используете raw для загрузки python на машину.
  • Если вы хотите выполнять команду безопасно и предсказуемо, может быть лучше использовать вместоних модули ansible.builtin.command или ansible.builtin.shell .
  • environment ключевого слово не работает с сырым нормально, это требует оболочки , которая означает , что он работает только тогда , когда executable установлен или с использованием модуля с эскалацией привилегий ( become ).
  • Этот модуль также поддерживается для целей Windows.

See Also

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

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

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

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

Examples

- name: Bootstrap a host without python2 installed raw: dnf install -y python2 python2-dnf libselinux-python - name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does) raw: cat  /tmp/*txt args: executable: /bin/bash - name: Safely use templated variables. Always use quote filter to avoid injection issues. raw: "> > install >" - name: List user accounts on a Windows system raw: Get-WmiObject -Class Win32_UserAccount 

Authors

Ansible

ansible.builtin.replace-Замена всех экземпляров определенной строки в файле с помощью регулярного выражения с обратной ссылкой

Источник

Ansible raw install python

This is one of my most popular articles. It was published on January 26 th 2019 and takes about 4 minutes to read.

Use it with caution — it is probably still valid, but it has not been updated for over a year.

How to install Python with Ansible

Ansible depends on Python to do its magic. Nonetheless it is possible to install Python on a server and thus prepare it for Ansible provisioning — with Ansible.

Table of contents

Watching Ansible provision a server from top to bottom and then deploy our Rails application is not onlyincredibly rewarding but also a safety net in case of desaster: It means that we can get back to a working state in a matter of minutes.

Before Ansible can take over, a Python interpreter must be present on the target machine. Manually installing Python is error prone and — if we need to do it regularly or on multiple machines — boring as hell.

Fortunately, it is possible to use Ansible to install Python on our server even when it actually depends on it — Ansible provides the raw module which can run basic low-down SSH commands on our server even if Python is not available.

Prepare a dedicated play

It makes sense to create a dedicated play for bootstrapping (we may even call it bootstrap.yml ), for two reasons:

  • We need to run its tasks as root (even if we plan to provision our server with a different user) because our server has to be considered fresh out of the box and therefore probably has no other users yet.
  • We need to turn off Ansible’s fact gathering with gather_facts: false . Fact gathering relies on Python so our play will crash if it is not already installed.
- hosts: all remote_user: root gather_facts: false tasks: 

Install Python 2

Even though Ansible claims to be compatible with Python 3, some modules still have glitches — it is safer to use Ansible 2.

Just because we do not have Python at our disposal yet does not mean that we cannot keep our tasks idempotent — we should always do that. So the first thing we do is checking whether Python is already installed or not:

 - name: Check for Python raw: test -e /usr/bin/python changed_when: false failed_when: false register: check_python 

This task runs the command test -e /usr/bin/python on our server which checks for the /usr/bin/python binary’s existence. This works because only the Python 2 binary is called python (Python 3’s interpreter is called python3 ).

We save this tasks’s result using Ansible’s register directive. We use this result to judge whether Python’s installation is necessary in the next task.

How we install Python depends on whether our server runs CentOS or Ubuntu. On CentOS systems we use yum :

 - name: Install Python raw: yum -y install python when: check_python.rc != 0 

On Ubuntu systems we use the apt command (and we have to update its cache):

 - name: Install Python raw: apt -y update && apt install -y python-minimal when: check_python.rc != 0 

If we need to support both CentOS and Ubuntu systems in a single play, we can apply this tasks for both operating systems in one fell swoop:

 - name: Install Python raw: test -e /usr/bin/apt && (apt -y update && apt install -y python-minimal) || (yum -y install python libselinux-python) when: check_python.rc != 0 

This works by first testing for the presence of the /usr/bin/apt command which is only present on Ubuntu systems.

By chaining subsequent commands with && , we make sure that they only run when this check evaluates to true . The yum command after the || , on the other hand, is only run when the test evaluates to false , meaning the apt command is not available (which only happens on CentOS systems).

Call the bootstrap play from our main playbook

Using Ansible’s import_playbook directive, we can now import this play into any playbook:

--- - import_playbook: bootstrap.yml 

Once our bootstrap play has completed, we can be sure that Python is available and we may continue to provision our server using any of Ansible’s wealth of modules.

The article you just read is a simplified version of one of the many useful techniques illustrated in my book Efficient Rails DevOps. Head over to its website to grab yourself a copy of the free sample chapter including its table if contents.

Get in the loop

Join my email list to get new articles delivered straight to your inbox and discounts on my products.

No spam — guaranteed.

Got it, thanks a lot!

Please check your emails for the confirmation request I just sent you. Once you clicked the link therein, you will no longer see these signup forms.

Michael Trojanek

Hörnesgasse 17 / 19
1030 Vienna
Austria

Источник

ansible.builtin.raw module – Executes a low-down and dirty command

This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name raw 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

  • Executes a low-down and dirty SSH command, not going through the module subsystem.
  • This is useful and should only be done in a few cases. A common case is installing python on a system without python installed by default. Another is speaking to any devices such as routers that do not have any Python installed. In any other case, using the ansible.builtin.shell or ansible.builtin.command module is much more appropriate.
  • Arguments given to raw are run directly through the configured remote shell.
  • Standard output, error output and return code are returned when available.
  • There is no change handler support for this module.
  • This module does not require python on the remote system, much like the ansible.builtin.script module.
  • This module is also supported for Windows targets.
  • If the command returns non UTF-8 data, it must be encoded to avoid issues. One option is to pipe the output through base64 .

This module has a corresponding action plugin .

Parameters

Change the shell used to execute the command. Should be an absolute path to the executable.

When using privilege escalation ( become ) a default shell will be assigned if one is not provided as privilege escalation requires a shell.

The raw module takes a free form command to run.

There is no parameter actually named ‘free form’; see the examples!

Attributes

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

Notes

  • If using raw from a playbook, you may need to disable fact gathering using gather_facts: no if you’re using raw to bootstrap python onto the machine.
  • If you want to execute a command securely and predictably, it may be better to use the ansible.builtin.command or ansible.builtin.shell modules instead.
  • The environment keyword does not work with raw normally, it requires a shell which means it only works if executable is set or using the module with privilege escalation ( become ).

See Also

Execute commands on targets.

Execute shell commands on targets.

Executes a command on a remote Windows node.

Execute shell commands on target hosts.

Examples

- name: Bootstrap a host without python2 installed ansible.builtin.raw: dnf install -y python2 python2-dnf libselinux-python - name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does) ansible.builtin.raw: cat < /tmp/*txtargs: executable: /bin/bash - name: Safely use templated variables. Always use quote filter to avoid injection issues. ansible.builtin.raw: " package_mgr|quote >>  pkg_flags|quote >> install  python|quote >>" - name: List user accounts on a Windows system ansible.builtin.raw: Get-WmiObject -Class Win32_UserAccount 

Authors

Источник

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