Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

In-depth Analysis of Linux lightweight automatic Operation and maintenance tool-Ansible

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Transferred from

Linux lightweight automatic Operation and maintenance tool-Ansible Analysis-~ Breeze ~-51CTO Technology blog

Http://weiweidefeng.blog.51cto.com/1957995/1895261

What is Ansible?

Ansible architecture diagram

Ansible characteristics

Modularization: call specific modules to complete specific tasks

Developed based on Python language, implemented by three core libraries: Paramiko, PyYAML and Jinja2

Simple deployment: agentless

Support custom modules and use any programming language

Powerful playbook mechanism

Idempotency

Installation and program environment:

Program:

Ansible

Ansible-playbook

Ansible-doc

Configuration file:

/ etc/ansible/ansible.cfg

Host list:

/ etc/ansible/hosts

Plug-in directory:

/ usr/share/ansible_plugins/

Install ansible

Install dependency packages

Use of the ansible command:

Usage: ansible [options]

Common options:

-m MOD_NAME

-a MOD_ARGS

Configure Host Inventory:

/ etc/ansible/hosts

[group_id]

HOST_PATTERN1

HOST_PATTERN2

Example:

Back up this file first in case you need to use the default configuration file later

Go to the / etc/ansible/hosts file, where the content below the green cursor is useless, it's all examples, you can delete it, and then add the host we used in the following experiment.

Add a set of websrvs servers for the following tests

Test host connectivity

The error here is caused by the exchange of the public / private keys of the other two hosts.

Experimental SSH password-free login settings

Generate private key and public key ssh-keygen-t rsa-P''

Copy the public key file and ask authorized_keys

Transfer the public key to another host

On the host of 68, you can see that the public key has been transferred and confirm whether the permissions of the file are correct.

Repeat the above to send the public key to the host of 69

Then re-execute the ping module command of ansible to check the connectivity of the two hosts

You can find that it has been successful at this time, so let's start to introduce other modules of ansilbe

Finally, remember to use ansible to synchronize the time of all hosts, so as to avoid errors in the time of a certain host, which will cause confusion if you look at the log later.

Ansible module:

Get module list: ansible-doc-l

Get help for using the specified module: ansible-doc-s MOD_NAME

Common modules:

Ping module: detect whether the target host is alive or not

Example: test the connectivity of all hosts

Command module: executing commands on remote host

Example 1: let all hosts synchronize time

The specified-m command command is not given here because the module of ansible is command by default

Example 2: have each host execute the uname-r command

Example 3: create a user on the host

Check whether the user has been created by two hosts

View user information:

To help these two users change their passwords, it should be noted that although the following command seems to have been executed successfully, when we verify it, we will find that the password is wrong. This is because ansible's command module does not support pipes and other outputs, so here is another ansible module shell.

Shell module: call the shell interpreter to run commands on the remote host, supporting various functions of shell, such as pipes, etc.

Note: the core parameters of command and shell modules are directly the command itself, while the parameters of other modules are usually in "key=value" format

Example: batch modification of passwords for specific users of other hosts

At this time, you can find that you can log in successfully.

Copy module: copying files to a remote host

Usage:

(1) copy files

-a "src=\"

(2) given content generation file

-a "content= dest="

Other parameters: mode, owner, group,...

Example: copy files to another host

Create a test file here

Copy files to another host

The following red error message is that if you want to transfer a file, the specified directory of the host needs to exist, if it does not exist, it is an error.

Create the corresponding directory

When you retransfer the file, there is no error prompt, but you can also see here that if the file already exists, the original file will be overwritten, and there is no prompt to overwrite the file, so you need to pay attention to the operation so as not to overwrite the important files.

Verify the file

File module: setting properties of a file

Usage:

(1) create a directory:

-a "path= state=directory"

(2) create a link file:

-a "path= src=\'#\'" / p >

(3) Delete files:

-a "path= state=absent"

Example: modify the permissions and owners of a file

Verify the file

Example: create a soft connection for a file

Verify the file

Set the status of the file to absent (that is, delete the file)

Verification

Fetch module: getting files from a remote host

Example: get a file from the 10.1.156.69 host

When you grab a pile of files, a directory of corresponding ip addresses is also created to distinguish the files.

Cron module: managing scheduled task entries

Usage:

-a "" minute=hour=day=month=weekday=job=name=user=state= {present | absent}

Example: create a scheduled task to synchronize time, synchronizing server time every 5 minutes

Verification task

Example: delete scheduled task

Verification

Hostname module: managing hostnam

Usage:

Name=

Example: modify hostname

Yum module: using the yum command to complete package management

Usage:

-a ""

(1) name= state= {present | latest}

(2) name= state=absent

Example: install the specified package

In this lab, first of all, make sure that the host's yum source is available, otherwise the lab will fail

Install samba package

Verification

Remove the samba installation package

There is no word for installation.

Service module: service management

Usage:

-a "" name=state=startedstoppedrestartedenabled=runlevel=

Example: enable the httpd service of the host

First, we confirm that the httpd service is turned off

Enable the httpd service and set it to boot

Verify that port 80 is open

Group modules: adding or deleting groups

Usage:

-a "" name=state=system=gid=

Example: add a group

Verification

Delete a group

Verification

User module: user management

Use format:

Name=: the user name created

State=: present added, absent deleted

Force=: delete the home directory when you delete a user

System=: create a system user

Uid=: specify UID

Shell=: specify shell

Home=: specify the user's home directory

Example: add a system user

Verification

Delete user

Setup module: collect all kinds of information in the host computer

Example: collect information for all hosts

YAML: a language format for data serialization tools

YAML is a data serialization format designed for human readability and interaction with scripting languages.

Data structure:

Key:value

-item1

-item2

-item3

For example, {name:jerry, age:21}

PlayBook

Core elements:

Tasks: task, list of actions defined by the module

Variables: variabl

Templates: templates, even text files that use template syntax

Handlers: Tasks triggered by a specific condition

Roles: roles

Basic components of playbook:

Hosts: the target host running the specified task

Remote_user: as which user to execute on the remote host

Sudo_user: non-administrator needs to have sudo permission

Tasks: task list

Module, module parameters:

Format:

(1) action: module arguments

(2) module: arguments

Run playbook, using the ansible-playbook command

(1) check syntax

Ansible-playbook-syntax-check / path/to/playbook.yaml

(2) Test run

Ansible-playbook-C / path/to/playbook.yaml

-- list-hosts

-list-tasks

-- list-tags

(3) run

Ansible-playbook / path/to/playbook.yaml

-t TAGS,-- tags=TAGS

-- skip-tags=SKIP_TAGS

-- start-at-task=START_AT

Example 1: define a playbook task to add users and groups

Define a template for yaml

Check the grammar to see if there are any mistakes. No hint means there should be no problem with the grammar.

Take a look at the test run.-C means only one side of the test run, but not the actual operation.

You can also test certain options separately.

View only affected hosts

See which tasks are running

Check which task is marked. There is no task marked here. We will demonstrate it later.

There are no errors above. Start running the task officially.

Verification

Example 2: define a playbook task to modify the file port

There is an installation package for installing httpd in this step, in fact, it is a bit redundant here, because the two hosts tested have already installed the service, and it is added here to demonstrate the effect, because in the production environment, if there is a server that does not have the installation package, then the next place can help us install it, otherwise, if you miss this step, it will be troublesome to find out the reason later.

Check for grammar problems

First copy the httpd.conf file from a mainframe to edit it.

Modify the httpd.conf file

For example, the port is changed to 8080, and the rest is the default configuration.

First of all, back up the configuration files in their respective hosts to prevent future errors.

Check whether the backup is successful

Test run web.yml to see if there is a problem, and run normally if there is no problem

Execute the revised document

Verify whether the server port is open or not, you can see that port 8080 has been opened, the experiment is successful.

Use of Handlers: Tasks triggered by specific conditions

Format:

Tasks:

-name: TASK_NAME

Module: arguments

Notify: HANDLER_NAME

Handlers:

-name: HANDLER_NAME

Module: arguments

Example: continue to modify the port of apache with reference to the example above

Change the port number to 8090

Modify the original web.yml script to implement the operation

Detection syntax

When the test runs, you can see that when the copy file is over, the handlers task of restart httpd service is triggered, so the task is restarted instead of started

Formal operation

Verification results show that port 8090 has been opened and the experiment is successful.

Tags: defines a call identity for the specified task

Use format:

-name: NAME

Module: arguments

Tags: TAG_ID

Example: perform a specific tags

Modify the port of the file to 8088

Insert a tag instconf above the previous configuration file

Check the grammar

You can see here that the yml script has a tag that affects the websrvs group

Test run

Run it formally, specifying to run under the label of instconf, so no other redundant information will be displayed here, including installing the httpd package and starting the httpd service

Verify the result

You can also mark multiple tags on the same file to execute at the same time.

Test run, because the httpd package and files have been installed here and copied, so they are all green. This is the end of the demonstration here. For other steps, you can refer to the above operation.

Variables: variabl

Type:

Built-in:

(1) facts

Customization:

(1) Command line transfer

-e VAR=VALUE

(2) define special variable values for each host in hosts Inventory

(a) pass different variables to different hosts

IP/HOSTNAME variable_name=value

(B) pass the same variable to all hosts in the group

[groupname:vars]

Variable_name=value

(3) defined in playbook

Vars:

-var_name: value

-var_name: value

(4) Inventory can also use parameters:

Used to define the properties used by ansible to connect remotely to the target host, rather than the variables passed to playbook

Ansible_ssh_host

Ansible_ssh_port

Ansible_ssh_user

Ansible_ssh_pass

Ansible_sudo_pass

...

(5) pass when the role is called

Roles:

-{role: ROLE_NAME, var: value,...}

Variable call:

{{var_name}}

Example 1: use the command line to pass variables to install different packages

Here {{pkgname}} is represented as a variable

Check the grammar, but I made a mistake. What's going on? Look carefully, even if you find that you have missed a space.

Add a space

Check again, there is still an error, do not panic, because this is only because the variable has not been assigned to the error will be reported, so it is normal to report an error here

Assign a value to the variable and run it again, so that the error will not be reported at this time.

Modify the variable, found that it is also normal, here 68 because vsftpd has been installed, so it will not be executed, so it will not changed

Example 2: define variables in playbook

There's no problem with the test.

Thinking? What if you pass the parameters of a variable using the parameters of-e at the same time?

The test results are as follows, is that the variable parameters passed by-e have higher priority, so that you can avoid errors due to the higher priority defined in the text?

Example 3: define a dedicated variable value for each host in hosts Inventory

Delete the original variables in the document

Test, no problem.

Example 4: the second way to define a dedicated variable value for each host in hosts Inventory

Testing is also possible.

Templates: templates, text files, embedded template language scripts (written in Jinja2 template language)

Jinja2 is a template engine written in pure Python. It provides a Django inspired non-XML syntax but supports inline expressions and an optional sandboxed environment.

Syntax:

Literal quantity:

Strings: using single or double quotation marks

Numbers: integers, floating point numbers

List: [item1, item2,...]

Tuple: (item1, item2,...)

Dictionary: {key1:value1, key2:value2,...}

Boolean: true/false

Arithmetic operation:

+, -, *, /,%, * *

Comparison operation:

=,! =, >, =

Example: install the MySQL package according to different systems

First define a template for tasks

Define a yaml calling role script

Set hosts file to add dbsrvs group

Test syntax

The test run calls the role script db.yml. There should be no big problem.

Officially run without reporting any errors

Verify that the service has been enabled

You can see that both mysql and mariadb services have been turned on

At the end, the ansible can control up to several hosts.

This is defined in the configuration file. The default is 5 hosts. If the host controlled by the host is enlarged, it is estimated that the host corresponding to the performance will be the ansible server.

Now that this blog post is over, here are a few points:

1. The format required by ansible playbook.yml files is relatively strict. Sometimes when a few spaces are missing, or when the spaces are not properly positioned, the system defaults to the wrong format, so you need to be careful.

2. Sometimes if you type an error that ansibile cannot recognize, you will not be prompted to test the file with-- syntax-check or-check. You need to actually run it in order to report an error.

3. Once when I wrote the playbook.yml file, I checked that there was no problem, but there was always something wrong with the test. Later, I just rewrote everything, or maybe I didn't see what was wrong.

Summary

The above is the Linux lightweight automatic operation and maintenance tool-Ansible, which is introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report