Ansible amazon linux extras

How do I install a software package from the Extras Library on an EC2 instance running Amazon Linux 2?

Last updated: 2020-10-07

How do I install a software package (known as a topic) from the amazon-linux-extras repository on an Amazon Elastic Compute Cloud (Amazon EC2) instance that’s running Amazon Linux 2?

Short description

To install a software package from the Extras Library, first confirm that the amazon-linux-extras repository is installed on your instance. Then, list the available software packages, enable the one you’re looking for, and then install the package using yum.

Note: This resolution is for Amazon Linux 2. These steps don’t apply to Amazon Linux 1 2018.03.

Resolution

2. Use the which command to confirm that the amazon-linux-extras package is installed:

If the amazon-linux-extras package isn’t installed, use yum to install it:

3. List the available topics.

Note: The repository is updated regularly, so the topics and versions that you see might differ from the following list.

4. Enable the desired topic. The output shows the commands required for installation. For example, to enable the PHP 7.2 topic, use the following command:

5. Install the topic using yum. For example, to install the PHP 7.2 topic, use the following command:

6. Use the following commands to verify the installation and confirm the software version:

Источник

Amazon + Ansible

+

В данной заметке хочу рассказать о некоторых приемах решений задач по связке ansible + amazon, может кому-то будет полезно или кто-то подскажет решения лучше. О установке/настройке ansible информации уже много, так что её я пропущу. О работе с amazon тоже ничего оригинального добавить не смогу. Итак, приступим.

Введение

Попросили помочь с разовой настройкой проекта, конкретно часть ansible + amazon, а так же конфигурация серверов на базе ubuntu и сервисов. Требования к проекты были выставлены такие:

  • Сервера балансировщики на nginx
  • N-е количество бэкендов nginx + nodejs
  • Сервер redis master
  • N-е количество redis slave
  • N-е количество windows servers ( что-то для криптографии, с условием готового шаблона)
  • Создавать очереди SQS
  • Создавать security groups
Примечание

Заказчик пожелал, что не нужно вносить правки на уже работающие сервера, если надо что-то поменять — меняют скрипты создания, сносят старое и создают новое… Хозяин — барин.

Работаем

Для большинства задач можно использовать модуль ec2. Модуль замечательный :), с большим количеством “подмодулей” почитать их описание можно тут: /usr/share/ansible/cloud (для ubuntu/debian).
В инвентарный файл ansible (hosts) нужно прописать всего 1 хост:

Я начал с самого простого, с windows server. Приведу пример playbook:

Тут все просто, ansible используя ваши aws_access_key и aws_secret_key посылает запрос в amazon на создание машинки с именем hostname=”Windows” типа instance_type=«t2.micro» из ранее созданого образа image=«ami-xxxxxxxx» в регионе region=«us-west-2» и присваивает sequrity group group=«launch-wizard-1» и больше ничего.

Читайте также:  Where is windows cmd

Далее сложнее, будем делать бэкенды nginx. Для начала все то же самое, создаем машину, но нужно с ней работать в этом же плэйбуке.
Создадим в кабинете amazon keypair, назовем его, например, aws_ansible. Скачиваем ключик и копируем его в

/.ssh/id_rsa пользователя из под которого запускаете плэйбуки.

Приведу в пример плэйбук создания бэкенда:

Теперь, что поменялось:
Мы указали, что для этой машинки использовать наш ключ keypair: «aws_ansible»
Указали образ чистой ubuntu image: «ami-33db9803».
С помощью registr и debug мы получили public_ip новой машинки и записали её во временную инвентаризацию в группу ec2hosts, записывать в hosts файл из плэйбука нельзя ( я не нашел как).
Следующим действием “wait for instances to listen on port:22” ждем когда станет доступен ssh.
И после всего этого выполняем обычные сценарии с обычным сервером, в моем случае установка/настройка nginx и nodejs

Еще я добавил Tag «Group»:«nginx_backend», это нужно для того что бы работать со всеми бэкендами сразу. Как? Есть скрипт подходящий для инвентаризации серверов amazon в ansible. Почитать о нем, а так же скачать его можно тут docs.ansible.com/intro_dynamic_inventory.html#id6.

Отлично, но у меня ситуация не много иная, мне нужно сделать upstream в nginx с неизвестным заранее количеством бэкендов. Побороздив просторы документации по ansible, не нашел как делать динамические списки. То есть подставлять динамически ip бэкенда — пожалуйста, а вот их количество менять… Как всегда на выручку пришел старый способ, написал велосипед ан python. не большой скрипт который вызывается из плэйбука до настройки nginx и генерирует конфиг с upstream.

Еще одна проблема была с redis master, его ip нужно было прописывать на каждый слэйв. Решил сделать с помощью include_vars.

При создании мастера до проверки доступности ssh делаю так:

В переменных указал:

Сам файл изначально должен быть и выглядит примерно так:

Затем в плейбуке настройки redis slave добавляем:

Используем переменную << master >> в шаблоне.

Sequrity group создается просто, используем модуль ec2_group:

Сложнее оказалось с очередями, модуля для них не нашлось, пытался даже доделать чьи-то попытки его написать. Но быстро опомнился и сделал через cloudformation.

Так выглядит плэйбук:

Резюме

Популярность облачных решений и систем управления конфигурациями растет, но я потратил порядочно времени выискивая варианты того или иного решения, собирая информацию и тд. Отсюда и родилась идея написать эту статью.

Источник

Automate Ansible playbook deployment with Amazon EC2 and GitHub

Ansible is an open-source automation tool that uses playbooks to enable you to make deployments faster and scale to various environments. Think of playbooks as recipes that lay out the steps needed to deploy policies, applications, configurations, and IT infrastructure. You can use playbooks repeatedly across multiple environments. Customers who use Ansible playbooks typically deploy periodic changes manually. As complex workloads increase, you might be looking for ways to automate them. In this post, we show you how to automate an Ansible playbook deployment using Amazon Elastic Compute Cloud (Amazon EC2) and GitHub.

In the section “Walkthrough for automating Ansible playbook deployment,” we explain how to configure the pipeline, step by step. In the section “Alternative procedure: Use an AWS CloudFormation template,” we present a quick and repeatable solution. You can modify either method to suit your requirements.

Читайте также:  Таймеры пробуждения windows для чего
About this blog post
Time to read 8 min.
Time to complete
(including deployment)

10 min. using CloudFormation

30 min. following the walkthrough steps

Cost to test the solution

$0

Learning level Advanced (300)
AWS services Amazon EC2
AWS CloudFormation
Amazon Linux 2

Process overview

The following diagram shows the pipeline flow.

A push event triggers a webhook request, which is sent to an Amazon EC2 instance. We use NGINX to route the request to an Express server running on the EC2 instance. The Express server then runs an Ansible command to pull and run the newly pushed playbook.

First, set up Ansible on an Amazon EC2 instance running an Amazon Linux 2 Amazon Machine Image (AMI) connected to a GitHub repository that stores your playbooks. Second, configure a webhook, which is a way for an app to send other applications real-time information during a push event. This allows you to automatically configure multiple environments, which saves you the time and energy that would have otherwise been spent on manual processes.

Prerequisites

This blog post assumes that you’re familiar with AWS CloudFormation templates, Amazon EC2, and GitHub.

For this walkthrough, you need the following:

  • An AWS account
  • An Amazon EC2 key pair
  • An Amazon EC2 instance running an Amazon Linux 2 AMI
  • A security group that allows SSH (Secure Shell) and HTTPS access
  • A GitHub repository to store playbooks

Walkthrough

Step 1: Set up webhook processing

To use Ansible with GitHub webhooks, set up webhook processing on the EC2 instance. This procedure uses NGINX as a reverse proxy to route the request to an Express server. Git is not required to process the webhook, but it is necessary for Ansible to pull the playbook from the repository.

  1. Access the EC2 instance using SSH. See Connecting to your Linux instance using SSH.
  2. Enable the Extra Packages for Enterprise Linux (EPEL) repository by running the following command.

The output looks like this:

Apply the updates to the packages.

Your webhook processing is now set up.

Step 2. Install Node.js and set up the Express server

  1. Choose a location for the Express server. In this example, we create a directory called server to store the relevant files.
    When the installation completes, create a JavaScript file that contains the code to handle the webhook request. We create a sample named app.js that runs the ansible-pull command to pull and run the playbook.yml file from a GitHub repository. The server is configured to listen on port 8080. You must know that the server is configured to listen on port 8080 because the NGINX configuration needs to know where to route the traffic that it receives. The port number is arbitrary, but the specification in the NGINX configuration file must match the port that is defined in the Express server code. In this example, replace , , and

with your information.

    Specify the GitHub user and repository where the playbooks are stored. This is required by the ansible-pull command. In this example, replace , , and

with your information.

Step 3. Set up a deploy key for your repository

  1. Create an SSH key on your instance. In this example, replace with your email address.

Keep the default settings, and press Enter to skip through the prompts.

  1. When the key is created, run the following code.

The output looks similar to this:

You will use this deploy key later in the procedure.

Step 4. Configure NGINX to route traffic

  1. Use the following basic configuration to listen on port 80 and route traffic to the port that the Express server listens to.

Step 5. Set up GitHub to configure the webhook

  1. Log in to your GitHub account, and navigate to your repository settings. The page looks like this:

  1. Add the deploy key from Step 3.
  2. On your instance, navigate to the .ssh directory, where the public key is stored.
  3. Open the id_rsa.pub file and copy its contents. In this example, replace with your email address. It should look like the following.
  1. Choose Add deploy key, and paste the contents into the Key section. The page looks like this:

  1. On the Webhooks tab, choose Add webhook.

  1. Copy and paste your EC2 instance’s public IP address into the Payload URL section. This adds the webhook that is triggered when a push event occurs. When the webhook is created and a request is sent to the EC2 instance, the Recent Deliveries section looks like this:

This response indicates that the Express server received the request.

Alternative procedure: Use an AWS CloudFormation template

Use the following AWS CloudFormation template to provision the Ansible stack. (See Creating a stack on the AWS CloudFormation console). This stack does not create the web server code or the NGINX configuration file. For a sample configuration and sample code, see the previous section, “Walkthrough for automating Ansible playbook deployment.” This AWS CloudFormation template runs only in the US East (N. Virginia) Region, and you must use a public subnet with internet access. To use this template in another Region, configure the Mappings section to match your Region with the latest AMI ID.

Cleanup

This procedure provisions an EC2 instance in your AWS account. If you choose an instance type within the free tier, it incurs no costs as long as it follows free-tier limits.

To remove your stack, see Deleting a stack on the AWS CloudFormation console. To remove your instance after provisioning the environment through the console, see Terminate your instance.

Conclusion

In this post, we walked through setting up a pipeline that enables you to deploy your Ansible playbooks through a push event using a combination of webhooks and Amazon EC2. We also provided an AWS CloudFormation template that spins up the resources automatically. Whichever method you choose, the configuration of multiple environments is automated to save time and energy. When you no longer must push playbooks manually, your system can respond to events in seconds using automated playbooks. This allows you to engineer a process that maintains consistency in your environment and ensures quality performance.

Please let us know your thoughts in the comments.

Источник

Читайте также:  Не найден файл bcd windows 10
Оцените статью