Install Ansible on Debian for Automation

Install Ansible on Debian for Automation

Here, ansible-pc is a Debian 10 machine where we will install Ansible.

The servers 6f7c2 and 6b219 are Debian 10 machines which we will configure for Ansible automation. I will simply call these servers Ansible hosts for the purpose of this article.

We can use Ansible from ansible-pc to automate different tasks in the 6f7c2 and 6b219 Debian servers.

Installing Ansible

In this section, I will show you how to install Ansible on ansible-pc.

You can install Ansible on Debian 10 from the official package repository of Debian.

First, update the APT package repository cache with the following command:

Now, install Ansible with the following command:

To confirm the installation, press Y and then press <Enter>.

Ansible should be installed.

Now, run the following command to check if Ansible is working correctly.

As you can see, the ansible command is available and is working correctly. Ansible 2.7.7 is the latest version of Ansible available in the Debian package repository at the time this article was written.

Generating SSH Key

On the Debian 10 machine (ansible-pc) where you have installed Ansible, you must first generate an SSH key.

To generate an SSH key, run the following command:

Now, press <Enter>.

Press <Enter>.

Press <Enter>.

An SSH key should be generated.

Configuring Debian Hosts for Ansible Automation

In this section, I will show you how to configure a Debian host for Ansible automation. If you have multiple hosts which you want to automate using Ansible, then repeat the same process for each of the hosts.

The hosts you would like to configure for Ansible automation must have the SSH server package pre-installed.

First, update the APT package repository cache with the following command:

Then, install the OpenSSH server with the following command:

In my case, the OpenSSH server package is already installed. If it is not installed in your case, then it should be installed prior to this step.

Now, check if the sshd service is running via the following command:

As you can see, the sshd service is active (running) and enabled (will automatically start on system boot).

If the sshd service is not active (running), start it manually with the following command:

If the sshd service is not enabled (not added to the system startup) in your case, add it to the system startup manually with the following command:

Now, create an ansible user and allow password-less sudo access to the ansible user.

To create an ansible user, run the following command:

Type in a password for the ansible user and press <Enter>.

Retype the password and press <Enter>.

An ansible user should be created.

Now, to allow password-less sudo access to the ansible user, edit the /etc/sudoers file with the following command:

Now, add the following line to the /etc/sudoers file.

Then, save the file by pressing <Ctrl> + X followed by Y, and then press <Enter>.

Now, find the IP address of the Ansible host 6f7c2 with the following command:

Here, the IP address in my case is 192.168.20.167. It will be different for you. So, make sure to replace this address with your own form now on.

Copying SSH Public Key to the Ansible Host

From the computer where you have installed Ansible (ansible-pc), copy the SSH public key to the Ansible host 6f7c2 as follows:

Type in yes and press <Enter>.

Next, type in the password for the ansible user and press <Enter>.

The public SSH key should be copied to Ansible host 6f7c2.

You should be able to SSH into the Ansible host 6f7c2 as the user ansible without any password, as you can see from the screenshot below:

You should also be able to run sudo commands without being prompted for any password.

Finally, close the SSH session as follows:

Securing Ansible Hosts

As the ansible user can run any sudo command without being prompted for a password, we have configured the SSH key based login for the Ansible hosts. But, you can still SSH into the Ansible hosts as ansible user using the password of the ansible user. So, this is not very secure.

To improve security, run the following command on the Ansible hosts to disable password-based login for the ansible user:

Читайте также:  76 миллиметровая пушка 1938 года

If you later decide to enable password-based login for the ansible user, run the following command on the Ansible host:

Testing Ansible

Create a new project directory

/project/ in the Debian machine where you have installed Ansible (ansible-pc) using the following code:

Navigate to the

/project/ directory using the following code:

Create a new hosts file in the project directory as follows:

Now, list the IP addresses or DNS names of the Ansible hosts (6f7c2 and 6b219 in my case) in the hosts file:

Once you are done, save the file by pressing <Ctrl> + X followed by Y and then hit <Enter>.

To test, try to ping all the hosts using Ansible with the following code:

NOTE: Here, the -u option is used to specify the username (ansible in this case) which Ansible will use to SSH into the hosts.

As you can see, Ansible can access all the hosts. So, the hosts are ready for Ansible automation.

So, that is how you install Ansible on Debian 10 and configure Debian hosts for Ansible automation. Thank you for reading this article.

Источник

Краткое руководство: Как установить и настроить Ansible в Linux для автоматизации

FavoriteДобавить в избранное

Главное меню » Операционная система Linux » Краткое руководство: Как установить и настроить Ansible в Linux для автоматизации

Краткое руководство: Как установить и настроить ansible в Linux для автоматизации

Почему необходимо установить и настроить Ansible в Linux.

Есть много таких инструментов, доступных для автоматизации, таких как Chef или Puppet. Однако эти инструменты имеют сложности в настройке. У нас есть отличная альтернатива для этих вариантов, это Ansible. С помощью ее, вы можете очень легко установить и настроить Ansible в Linux.

Это руководство быстро расскажет вам о том, как установить и настроить Ansible в Linux.

Сколько Ansible работает!

Ansible не использует какие-либо средства для выполнения задач автоматизации, а это значит, что нет никаких фоновых процессов работающих на клиентах. Вместо этого, Ansible делает соединение с использованием SSH для осуществления своих операций.

Детали установки для установки Ansible.

Детали для сервера управления Ansible:

Детали машины клиента:

Шаг 1: Установка Ansible на сервере управления.

Для Linux Mint, Ubuntu и Debian
Для RHEL, CentOS и Fedora

Пожалуйста, обратите внимание, что нет никакого официального репозитория Ansible для RedHat, мы все еще можем установить Ansible, добавляя репозиторий Epel под RHEL или Centos.

После установки Ansible вы можете проверить версию с помощью следующей команды.

Шаг 2: Настройка SSH для настройки Ansible.

Для развертывания или управления на клиентской машине с нашего сервера управления «destroyer», нам нужно установить пароль на SSH между ними. В этой демонстрации мы настроили пользователя lradmin для пароля SSH.

Генерировать ключи SSH на сервере управления для пользователя lradmin.

Здесь мы сделали генерацию ключей, в следующем шаге нам необходимо скопировать содержимое «/root/.ssh/id_rsa.pub» на клиентскую систему для пользователя lradmin. Пожалуйста, следуйте инструкциям, приведенные в этом посте, так чтобы пароль имел связь между сервером управления и машиной клиента web1 и web2.

После того, как вы закончите с паролем конфигурации, вы можете перепроверить, делая SSH, как показано ниже.

Шаг 3: Создание файла инвентаризации для Ansible.

На следующем этапе нам нужно создать файл инвентаризации для списка клиентов. В основном его список IP клиента или имя хоста для машин, которые используются для автоматизации.

Пожалуйста, добавьте ниже строки кода в файл “/etc/Ansible/hosts” на нашем сервере управления.

Приведенные выше строки кода описывают, как список клиентских машин подпадает под категорию веб-пользователя, имеющего Ansible как lradmin.

Шаг 4: Проверьте соединение.

Теперь пришло время, чтобы проверить, является ли наша конфигурация правильно установлена или нет. Для этого мы будем использовать пинг в Ansible.

В приведенной выше команде мы использовали пинг для нашего веб – сервера.

Система должна ответить сообщением ниже, если все Ok.

Шаг 4: Выполнение удаленных команд на клиентских машинах.

Теперь мы имеем возможность запускать произвольные команды на клиентских машинах, чтобы извлечь некоторую информацию о них. Таким образом, чтобы сделать это, необходимо использовать модуль «command» в пределах Ansiblensible.

  • В случае, если вы хотите использовать файловую систему на клиентской машине.
Проверка бесперебойной работы клиентских машин.

Вывод:

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

How to Install Ansible AWX on Debian 10

Ansible is a free and open-source configuration management and automation tool used to manage hundreds and thousands of servers from a central location.

Читайте также:  Примите жалобу куда и на что жаловаться автомобилистам

Ansible AWX is an open-source project, sponsored by Red Hat, that helps you control Ansible in IT environments. It provides a web-based interface REST API and task engine for Ansible. You can manage playbooks, secrets, inventories, and cron jobs using the AWX web-based interface.

In this tutorial, we will show you how to install Ansible AWX with Docker on Debian 10.

Prerequisites

  • A fresh Debian 10 VPS on the Atlantic.net Cloud Platform
  • A root password configured on your server

Step 1 – Create an Atlantic.Net Cloud Server

First, log in to your Atlantic.Net Cloud Server. Create a new server, choosing Debian 10 as the operating system, with at least 4GB RAM. Connect to your Cloud Server via SSH and log in using the credentials highlighted at the top of the page.

Once you are logged in to your Debian 10 server, run the following command to update your base system with the latest available packages.

Step 2 – Install Docker

First, you will need to install the Docker and Docker compose in your system. By default, the latest version of Docker is not available in the Debian standard repository, so you will need to add the Docker repository to your system.

Install the required dependencies with the following command:

Next, download and add the Docker GPG key with the following command:

Next, add the Docker repository with the following command:

Next, update the Docker repository and install Docker with Docker compose using the following command:

Once both packages are installed, verify the installed version of Docker with the following command:

You should get the following output:

Step 2 – Install Ansible

AWX is built on the top of the Ansible. so you will need to install Ansible in your system.

First, add the Ansible repository with the following command:

Next, update the repository and install the Ansible with the following command:

Once the Ansible is installed, verify the installed version of Ansible using the following command:

You should get the following output:

Step 3 – Install Node.js and Python Library

First, install the Node.js, NPM and Git with the following command:

Next, install the Python module for Docker and other required dependencies with the following command:

Next, update the default Python version with the following command:

Next, you will need to install Docker compose Python module in your system.

First, check the installed version of Docker compose with the following command:

You should get the following output:

Next, installed the matching version of Docker compose Python module with the following command:

Step 4 – Install Ansible AWX

First, download the latest version of AWX source from the Git repository using the following command:

Once downloaded, change the directory to awx and generate the secrete key with the following command:

You should get the following output:

Next, create a new inventory file with the following command:

Add the following lines including, admin user, password, secret key, port, and hostname as shown below:

Save and close the file when you are finished.

Next, run the playbook to install the Ansible AWX with the following command:

Once the Ansible AWX has been installed, you should get the following output:

Next, you can verify the list of running containers using the following command:

You should get the following output:

Step 5 – Access Ansible AWX Dashboard

Now, open your web browser and access the Ansible AWX dashboard using the URL http://your-server-ip. You will be redirected to the AWX login page:

Provide your admin username and password that you have defined in the inventory file and click on the SIGN IN button. You should see the Ansible AWX dashboard on the following page:

Conclusion

Congratulations! You have successfully installed Ansible AWX with Docker on Debian 10. You can now easily control Ansible inventory, secrets, playbooks, and more from the AWX dashboard; try it now on VPS Hosting from Atlantic.Net!

Free Tier Includes:
G3.2GB Cloud VPS Free to Use for One Year
50 GB of Block Storage Free to Use for One Year
50 GB of Snapshots Free to Use for One Year

Читайте также:  Новые темы для оформления Windows 7 by Leha342 04 12 x86 x64 2014 RUS

Looking for a Hosting Solution?

We Provide Cloud, Dedicated, & Colocation.

  • Seven Global Data Center Locations.
  • Flexible Private, Public, & Hybrid Hosting.
  • 24x7x365 Security, Support, & Monitoring.

Get started with 12 months of free cloud VPS hosting

Free Tier includes:
G3.2GB Cloud VPS Server Free to Use for One Year
50 GB of Block Storage Free to Use for One Year
50 GB of Snapshots Free to Use for One Year

Источник



Как установить и использовать Ansible в Debian 10

Сегодня TipsMake представит процесс установки Ansible в Debian 10.

Установка Ansible на Debian 10

Чтобы установить Ansible в Debian 10, вам нужно сделать три простых шага:

Шаг 1. Обновите свою систему Debian 10

Перед установкой Ansible в Debian 10 вы должны обновить его, используя команду, показанную ниже:
sudo apt update
После обновления вашей системы Debian 10 вы должны увидеть в Терминале информацию, как показано на следующем изображении:

Изображение 1 из Как установить и использовать Ansible в Debian 10

Шаг 2. Установите Ansible в системе Debian 10

После завершения обновления системы вы можете установить Ansible в Debian 10, используя команду, показанную ниже:
sudo apt install ansible
Во время выполнения этой команды вы увидите сообщение с вопросом, хотите ли вы продолжить установку в Терминале. Вы должны ввести Y, чтобы установка продолжалась без сбоев.

Когда Ansible успешно установлен в системе Debian 10, Терминал сгенерирует на нем какое-то сообщение, подобное показанному на следующем рисунке:

Изображение 2 из Как установить и использовать Ansible в Debian 10

Шаг 3: Подтверждение установки Ansible в системе Debian 10

Установка Ansible в системе Debian 10 настолько проста, что ее нужно выполнить за два шага, описанных выше. Однако вы все равно можете проверить, был ли он успешно установлен в вашей системе Debian 10. Это можно сделать, проверив версию Ansible с помощью следующей команды:
ansible –version
Версия Ansible, установленная в системе Debian 10 в этом примере, – 2.7.7.

Отредактируйте файл host / etc / ansible / hosts, чтобы добавить систему, которой вы хотите управлять с помощью Ansible.
Судо нано / и т. д. / ansible / hosts
Пожалуйста, добавьте следующее:
[TestClient] узел1 ansible_ssh_host = 192.168.0.12
И сохраните файл.

Использовать Ansible

Во-первых, вы должны настроить SSH-ключ для клиентского узла, поскольку Ansible использует протокол SSH для передачи команд клиентской системе.

Используйте эту команду для генерации ключа SSH и аутентификации на основе ключа:
ssh-keygen
Выход:
Создание пары ключей открытого и закрытого типа RSA. Введите файл, в котором нужно сохранить ключ (/root/.ssh/id_rsa): Введите кодовую фразу (пусто, если кодовая фраза отсутствует): Введите ту же парольную фразу еще раз: Ваш идентификатор был сохранен в /root/.ssh/id_rsa. Ваш открытый ключ сохранен в /root/.ssh/id_rsa.pub. Отпечаток ключа: SHA256: gTHiTCK …. root @ debian10 Случайное изображение ключа: + —[RSA 2048]—- + | . . . | + —-[SHA256]—– +
Следующим шагом является копирование вновь созданного ключа в другую систему. Выполните эту команду:
ssh-copy-id -i

/ .ssh / id_rsa.pub root@192.168.0.2
IP 192.168.0.2 в приведенной выше команде следует заменить IP-адресом системы, которой вы хотите управлять с помощью Ansible.

Выход:
/ usr / bin / ssh-copy-id: INFO: Источник ключа (ов) для установки: “/root/.ssh/id_rsa.pub” / usr / bin / ssh-copy-id: INFO: попытка регистрации с новым ключом (ключами), чтобы отфильтровать все, что уже установлено / usr / bin / ssh-copy-id: ИНФОРМАЦИЯ: осталось установить 1 ключ (и) – если вам будет предложено сейчас, он должен установить новые ключи root@192.168.0.2 пароль: Количество добавленных ключей: 1
Теперь, когда пришло время провести первый тест, войдите в систему на другом компьютере, используя эту команду SSH:
ssh root@192.168.0.2
Теперь логин должен работать без пароля.

Тестовый запуск Ansible

Установка завершена, теперь вы можете приступить к тестированию Ansible.

Выполните эту команду, чтобы проверить соединение:
ansible -m ping TestClient
Выход:
node1 | УСПЕХ => <“изменено”: false, “ping”: “pong”>
Если вы определили несколько клиентов, вы можете проверить все соединения с помощью следующей команды:
ansible -m пинговать все
Теперь пора запустить команду в удаленной системе и получить результаты. В этом примере будет использоваться команда df.
ansible -m оболочка -a ‘df -h’ TestClient
Выход:
node1 | ИЗМЕНЕНО | rc = 0 >> Размер используемой файловой системы Доступность Использование% Установлено на udev 957M 0 957M 0% / dev tmpfs 195M 21M 175M 11% / run / dev / sda1 38G 11G 25G 31% / tmpfs 974M 0 974M 0% / dev / shm tmpfs 5.0M 0 5.0M 0% / run / lock tmpfs 974M 0 974M 0% / sys / fs / cgroup / dev / sda15 121M 130K 120M 1% / boot / efi tmpfs 195M 0 195M 0% / run / user / 0
Результаты показывают использование жесткого диска в удаленной системе. Вы можете выполнить любую команду оболочки Linux, подобную этой, с помощью Ansible, а также создать полный сценарий для настройки и обслуживания сервера.

Источник