Conversation with Merlin [email protected] · Thu Nov 09 2023

Description: This playbook updates the API on a remote system and optionally checks its health.

It assumes some setup requirements, including certain environment configuration and user permissions.

  • hosts: "all" gather_facts: no ignore_errors: no

    vars:

    Set API build source and destination variables

    api_build_file: "sample_path/api_build/{{ build_file }}" # Use sample paths and names api_build_src: /{{ api_build_file }} api_build_dest: /sample_path/api_dest

    Set variables for connection

    ansible_become_user: sample_user ansible_connection: sample_connection ansible_sample_region: sample_region

    API check script variables

    check_api: true check_script_src: /sample_path/check_api_mock.sh check_script_dest: /sample_path_dest/check_api_mock.sh

    tasks:

    • name: "Find old API files to delete in application directory" find: paths: /sample_path/api_dest patterns: 'sample_file_pattern' register: files_to_delete

    • name: "Remove old API files" file: path: "{{ item.path }}" state: absent with_items: "{{ files_to_delete.files }}"

    • name: "Copy API build to the destination" copy: remote_src: no force: yes src: "{{ api_build_src }}" dest: "{{ api_build_dest }}" owner: sample_user group: sample_user mode: '0774'

    • name: "Decompress API build archive" unarchive: remote_src: yes src: "{{ api_build_dest }}/{{ build_file }}" dest: "{{ api_build_dest }}"

    • name: "Set permissions on API build files" shell: chown -R sample_user "{{ api_build_dest }}" && chgrp -R sample_user "{{ api_build_dest }}" && chmod -R 775 "{{ api_build_dest }}"

    • name: "Copy API check script to the remote system" when: check_api == true copy: remote_src: no force: yes src: "{{ check_script_src }}" dest: "{{ check_script_dest }}" owner: sample_user group: sample_user mode: '0774'

    • name: "Restart API" become: true shell: . ~/.profile ; sample_api_command register: restart_output

    • debug: msg="{{ restart_output.stdout_lines }}"

    • name: "API validation script" become: true when: check_api == true shell: sleep 30 && chmod +x "{{ check_script_dest }}" && bash "{{ check_script_dest }}" register: check_output

    • name: "API validation script results" when: check_api == true debug: msg="{{ check_output.stdout_lines }}" Read the above code and explain line by line

  1. The playbook is described at the beginning with comments identifying its purpose and assumptions about environment configuration user permissions.

  2. Next, it specifies the target hosts, whether to gather facts, and whether to ignore errors.

  3. It various variables related to the API build source and destination, connection details, region, and for checking API health.

  4. The tasks section contains the actual operations to be executed on the remote system.

  5. First, it finds old API files to delete in the application directory.

  6. Then, it removes the old API files.

  7. Next, it copies the API build to the destination, sets the permissions, and decompresses the API build archive.

  8. It then copies the API check script to the remote system and restarts the API.

  9. Finally, it runs a validation script to check the API's health and displays the results.

The playbook follows a sequence of tasks to update the API on a remote system and optionally check its health, using defined variables and subtasks for managing the API build and script files. Each task is named and has specific actions, such as file manipulation, copying, permission setting, and script execution, to achieve the overall goal of updating the API.

// Tutorial Series //How To Write Ansible PlaybooksIntroductionIntroduction Ansible is a modern configuration management tool that doesnt require the use of an agent software on remote nodes. Instead, it uses only SSH and Python to communicate and execute commands on managed servers. Ansible allows users to manage servers in two different ways: via ad hoc commands, and via playbooks. Playbooks are YAML files containing a list of ordered tasks that should be executed on a remote server to complete a task or reach a certain goal, such as to set up a LEMP environment. Ansible playbooks allow you to fully automate server setup and application deployment, using an accessible syntax and an extensive library of built-in resources. This series will walk you through some of Ansibles main features which you can use to write playbooks for server automation. At the end, youll create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it. The playbook examples used in this series can be found in our ansible-practice repository at the DigitalOcean Community organization on GitHub. Prerequisites In order to follow along with the practical examples in this series, youll need: One Ansible Control Node: The Ansible control node is the machine well use to connect to and control the Ansible hosts over SSH. Your Ansible control node can either be your local machine or a server dedicated to running Ansible, though this series assumes your control node is an Ubuntu 20.04 system. Make sure the control node has a non-root user with sudo privileges. To set this up, you can follow Steps 2 and 3 of our Initial Server Setup Guide for Ubuntu 20.04. However, please note that if youre using a remote server as your Ansible Control node, you should follow every step of this guide. Doing so will configure a firewall on the server with ufw and enable external access to your non-root user profile, both of which will help keep the remote server secure. An SSH keypair associated with your control nodes non-root user. To set this up, you can follow Step 1 of our guide on How to Set Up SSH Keys on Ubuntu 20.04. One or more Ansible Hosts: An Ansible host is any machine that your Ansible control node is configured to automate. This guide assumes your Ansible hosts are remote Ubuntu 20.04 servers. Make sure each Ansible host has the Ansible control nodes SSH public key added to the authorized_keys of a system user. This user can be either root or a regular user with sudo privileges. To set this up, you can follow Step 2 of How to Set Up SSH Keys on Ubuntu 20.04. Ansible installed and configured on your control node. To set up Ansible, please follow our guide on How to Install and Configure Ansible on Ubuntu 20.04. A working Ansible inventory file. This inventory file should be set up on your control node and should contain all of your Ansible hosts. The guide How To Set Up Ansible Inventories explains in detail how you can create an Ansible inventory file. Once you have met these prerequisites, run a connection test as outlined in our guide on How To Manage Multiple Servers with Ansible Ad Hoc Commands to make sure youre able to connect and execute Ansible instructions on your remote nodes. Summary Viewdetailed View// Tutorial //Playbooks use the YAML format to define one or more plays. A play is a set of ordered tasks that are arranged in a way to automate a process, such as setting up a web server or deploying an application to production. In a playbook file, plays are defined as a YAML list. A typical play starts off by determining which hosts are the target of that particular setup. This is done with the hosts directive. Setting the hosts directive to all is a common choice because you can limit the targets of a play at execution time by running the ansible-playbook command with the -l parameter. That allows you to run the same playbook on different servers or groups without the need to change the playbook file every time.

digitalocean.com

What is Ansible? Ansible is an open source automation and orchestration tool for software provisioning, configuration management, and software deployment. Ansible can easily run and configure Unix-like systems as well as Windows systems to provide infrastructure as code. It contains its own declarative programming language for system configuration and management. Ansible is popular for its simplicity of installation, ease of use in what concerns the connectivity to clients, its lack of agent for Ansible clients and the multitude of skills. It functions by connecting via SSH to the clients, so it doesnt need a special agent on the client-side, and by pushing modules to the clients, the modules are then executed locally on the client-side and the output is pushed back to the Ansible server. Since it uses SSH, it can very easily connect to clients using SSH-Keys, simplifying though the whole process. Client details, like hostnames or IP addresses and SSH ports, are stored in files called inventory files. Once you have created an inventory file and populated it, ansible can use it. Why use Ansible? Here are some important pros/benefits of using Ansible One of the most significant advantages of Ansible is that it is free to use by everyone. It does not need any special system administrator skills to install and use Ansible, and the official documentation is very comprehensive. Its modularity regarding plugins, modules, inventories, and playbooks make Ansible the perfect companion to orchestrate large environments. Ansible is very lightweight and consistent, and no constraints regarding the operating system or underlying hardware are present. It is also very secure due to its agentless capabilities and due to the use of OpenSSH security features. Another advantage that encourages the adoption of Ansible is its smooth learning curve determined by the comprehensive documentation and easy to learn structure and configuration. History of Ansible Here, are important land marks from the history of ansible: In February 2012 the Ansible project began. It was first developed by Michael DeHaan, the creator of Cobbler and Func, Fedora Unified Network Controller. Initially called AnsibleWorks Inc, the company funding the ansible tool was acquired in 2015 by RedHat and later on, along with RedHat, moved under the umbrella of IBM. In the present, Ansible comes included in distributions like Fedora Linux, RHEL, Centos and Oracle Linux. Important terms used in Ansible Ansible server The machine where Ansible is installed and from which all tasks and playbooks will be ran Module Basically, a module is a command or set of similar Ansible commands meant to be executed on the client-side Task A task is a section that consists of a single procedure to be completed Role A way of organizing tasks and related files to be later called in a playbook Fact Information fetched from the client system from the global variables with the gather-facts operation Inventory File containing data about the ansible client servers. Defined in later examples as hosts file Play Execution of a playbook Handler Task which is called only if a notifier is present Notifier Section attributed to a task which calls a handler if the output is changed Tag Name set to a task which can be used later on to issue just that specific task or group of tasks. Ansible Installation in Linux Once you have compared and weighed your options and decided to go for Ansible, the next step is to have it installed on your system. We will go through the steps of installation in different Linux distributions, the most popular ones, in the next small tutorial. Install Ansible on Centos/RedHat systems Step 1) Install EPEL repo [root@ansible-server ~]# sudo yum install epel-release Step 2) Install ansible package [root@ansible-server ~]# sudo yum install -y ansible Install ansible on Ubuntu/Debian systems Step 1) Perform an update to the packages $ sudo apt update Step 2) Install the software-properties-co

guru99.com

In this article, we are exploring Ansible Playbooks, which are basically blueprints for automation actions. Playbooks allow us to define a recipe with all the steps we would like to automate in a repeatable, simple, and consistent manner. If you are entirely new to Ansible, check out this introductory Ansible Tutorial first. What is an Ansible Playbook?Playbooks are one of the basic components of Ansible as they record and execute Ansibles configuration. Generally, a playbook is the primary way to automate a set of tasks that we would like to perform on a remote machine. They help our automation efforts by gathering all the resources necessary to orchestrate ordered processes or avoid repeating manual actions. Playbooks can be reused and shared between persons, and they are designed to be human-friendly and easy to write in YAML. Playbook StructureA playbook is composed of one or more plays to run in a specific order. A play is an ordered list of tasks to run against the desired group of hosts. Every task is associated with a module responsible for an action and its configuration parameters. Since most tasks are idempotent, we can safely rerun a playbook without any issue. As discussed, playbooks are written in YAML using the standard extension .yml with minimal syntax. We must use spaces to align data elements that share the same hierarchy for indentation. Items that are children of other items must be indented more than their parents. There is no strict rule for the number of spaces used for indentation, but its pretty common to use two spaces while Tab characters are not allowed. Below is an example simple playbook with only two plays, each one having two tasks: --- - name: Example Simple Playbook hosts: all become: yes tasks: - name: Copy file example_file to /tmp with permissions ansible.builtin.copy: src: ./example_file dest: /tmp/example_file mode: '0644' - name: Add the user 'bob' with a specific uid ansible.builtin.user: name: bob state: present uid: 1040 - name: Update postgres servers hosts: databases become: yes tasks: - name: Ensure postgres DB is at the latest version ansible.builtin.yum: name: postgresql state: latest - name: Ensure that postgresql is started ansible.builtin.service: name: postgresql state: startedWe define a descriptive name for each play according to its purpose on the top level. Then we represent the group of hosts on which the play will be executed, taken from the inventory. Finally, we define that these plays should be executed as the root user with the become option set to yes. You can also define many other Playbook Keywords at different levels such as play, tasks, playbook to configure Ansibles behavior. Even more, most of these can be set at runtime as command-line flags in the ansible configuration file, ansible.cfg, or the inventory. Check out the precedence rules to understand how Ansible behaves in these cases. Next, we use the tasks parameter to define the list of tasks for each play. For each task, we define a clear and descriptive name. Every task leverages a module to perform a specific operation. For example, the first task of the first play uses the ansible.builtin.copy module. Along with the module, we usually have to define some module arguments. For the second task of the first play, we use the module ansible.builtin.user that helps us manage user accounts. In this specific case, we configure the name of the user, the state of the user account, and its uid accordingly. Running a PlaybookWhen we are running a playbook, Ansible executes each task in order, one at a time, for all the hosts that we selected. This default behavior could be adjusted according to different use cases using strategies. If a task fails, Ansible stops the execution of the playbook to this specific host but continues to others that succeeded. During execution, Ansible displays some information about connection status, task names, execution status, and if any changes have been performed. At the end, Ans

spacelift.io