Initial use of ansible and introduction to YAML syntax

Source: Internet
Author: User
Tags file copy ansible playbook ansible modules saltstack

I. INTRODUCTION 

1. Introduction to ansible

Ansible's official title is "Ansible is Simple IT Automation"-a Simple automated IT tool. The goal of this tool is to automate APP deployment, automate configuration management, automate continuous delivery, and automate (AWS) cloud service management.

All these goals are essentially executed on one or several servers, and if you want to manage thousands of servers, if you use a server to manage and control a large number of servers, it will inevitably lead to considerable resource consumption and low performance of the host machine (even if you can use the ansible-f parameter for parallel execution ), in this case, a p2p concept is required, so that each synchronization and Configuration Server can be used as an ansible central control machine to configure other servers simultaneously.

2. Powerful automated O & M tools

Powerful automatic chemical products include ansible, puppet, and saltstack.

Both puppet and saltstack need to install clients. saltstack and ansible are similar and belong to python streams, but saltstack is not very stable, therefore, the search rate of ansible is three times that of saltstack. Although puppet is stable, it is very troublesome to configure the module during command execution, and you also need to install the client. If the company is in a cooperative relationship with other companies, obviously, installing the client is a factor that has to be considered; therefore, ansible is not inferior to the two tools in terms of performance and is not cumbersome to use. The key ansible is developed based on paramiko, paramiko is a Python-only ssh Protocol Library. Ansible does not need to install client/agents on the remote host because it communicates with the remote host based on ssh.

3. Features of ansible

(1) No agents: No need to install any client on the controlled host;

(2) No server: No server. You can directly run the command when using it;

(3) Modules in any languages ages: Modules can be developed in any language.

(4) YAML, not code: Use the yaml language to customize the script playbook;

(5) SSH by default: work based on SSH;

(6) Strong multi-tier solution: multi-level command can be implemented;

II. Basic use of ansible

1. Install ansible

[[Email protected] ~] # Yum install-y ansible

2. Main files

[[Email protected] ~] # Ls/etc/ansible. cfg # Master configuration file, do not modify hosts # add the host group to be operated

3. ansible format

Ansible 

4. View the usage of each module

Ansible-doc [options] [modules]: Show Ansible module documentation-l list all ansible modules-s list related commands of this module

5. Use ansible for the first time

(1) install ansible

[[Email protected] ~] # Yum install-y ansible

(2) host-pattern)

# Vim/etc/ansible/hosts [web servers] 192.168.200.211192.168.200.212192.168.200.192.168.200.214 [db servers] 192.168.200.215192.168.200.216

(3) Create an SSH public key and private key

[[Email protected] ~] # Ssh-keygen

(4) copy the public key file to the target server [Note: ssh-copy-id: append the public key to. ssh/authorized_key of the remote host.]

[[Email protected] ~] # Ssh-copy-id [email protected] [[email protected] ~] # Ssh-copy-id [email protected] [[email protected] ~] # Ssh-copy-id [email protected]...

(5) connection and verification test

[[Email protected] ~] # Ansible-I/etc/ansible/hosts all-m ping

(6) module

View the usage of each module

Ansible-doc [options] [modules]: Show Ansible module documentation-l list all ansible modules-s list related commands of this module

Examples

Ansible all-a "/bin/echo hello" (do not write-m, the default module is shell) ansible all-m command-a "/bin/echo hello, world "ansible all-m shell-a" ping baidu.com-c 1 "ansible all-m ping # The ping operation-I parameter is not specified, the default value is/etc/ansible/hostsansible "web servers"-a 'date' (-m command can be omitted) # execute the date command ansible "db servers"-m copy-a "src =/root/ansible. rpm dest =/tmp/"# copy the file ansible all-m cron-a 'name =" custom job "minute = */3 hour = * day = * month = * weekday = * job = "/usr/sbin/ntpdate 192.168.200.16" '# configure the crontab task ansible all-m group-a "name = mysql gid = 36 system = yes" # Add groups and users ansible corosync-m yum-a "name = httpd state = present" # install httpdansible all-m service-a "name = httpd state = started enabled = yes" # configuration service through yum enable startup

Common Modules

Common Modules: copy, command, service, yum, apt, file, raw, shell, script, cron, user, state, template,

Ansible-I/etc/ansiblehosts all-m 'service'-a' name = httpd state = stoped 'ansible-m yum-a' name = gcc state = present'

The yum module is often used to install software.

The service module is often used to switch services.

The shell module can be used to execute commands and scripts.

Raw is similar to command and shell, but it can pass pipelines

III. YAML syntax

YAML Ain't Markup Language, that is, YAML is not XML. However, when developing this Language, YAML actually means: "Yet Another Markup Language" (still a Markup Language ).

The syntax of YAML is similar to that of other high-level languages, and it can easily express data structures such as list, hash, and scalar. Its Structure is displayed by spaces. The items in the Sequence are represented by "-", and the key-value pairs in Map are separated. The following is an example.

The YAML file extension is usually. yaml, for example, example. yaml.

Name: John Smithage: 41 gender: Malespouse: name: Jane Smith age: 37 gender: Femalechildren:-name: Jimmy Smith age: 17 gender: Male-name: jenny Smith age 13 gender: Female

4. ansible playbook)

    Playbook usage: ansible-playbook test. yaml

Playbook is a list composed of one or more "play. The main function of play is to combine a group of hosts into a role defined by task in ansible. Basically, a task is nothing more than a module that calls ansible. Organize multiple plays in one playbook, so that they can be joined together and sing a single drama in a pre-arranged manner.

# This is the host you selected-hosts: webservers # This is the variable vars: http_port: 80 max_clients: 200 # remote execution permission remote_user: root tasks: # Use the yum module to operate-name: ensure apache is at the latest version yum: pkg = httpd state = latest-name: write the apache config file template: src =/srv/httpd. j2 dest =/etc/httpd. conf # restart the server restart Y:-restart apache-name: ensure apache is running service: name = httpd state = started # Here restart apache and the above trigger Sending is paired. This is the role of handlers. Equivalent to tag handlers:-name: restart apache service: name = httpd state = restarted

1. HOSTS and Users

In playbook, each play aims to allow a host or some hosts to execute tasks as a specified user.

Hosts is used to specify the host for executing the specified task. It can be one or more host groups separated by colons;

Remote_user specifies the user who executes the task on the remote host. As shown in the preceding example

-Hosts: webnodes remote_user: root

However, remote_user can also be used in each task. You can also specify sudo to execute tasks on a remote host, which can be used to play a global task or a task. In addition, you can even use sudo_user to specify the user to switch to when sudo is used in sudo.

-Hosts: webnodes remote_user: root tasks:-name: test connection ping: remote_user: root sudo: yes

2. Task list and cation

The main part of play is the task list. Tasks in the task list are executed on all hosts specified in hosts one by one, that is, the first task is completed on all hosts before the second task starts. When an error occurs in the middle of a playbook while running the current script, all executed tasks will be rolled back. Therefore, you can correct the playbook and execute it again.

The purpose of a task is to use the specified parameter execution module, while a variable can be used in the module parameters. The module execution is idempotent, which means that multiple executions are safe because the results are consistent.

Each task should have its name, which is used to output the execution result of the playbook. We recommend that you describe the task execution steps as clearly as possible. If name is not provided, the action result is used for output.

You can use the "action: module options" or "module: options" format to define a task. We recommend that you use the latter for backward compatibility. If an action row contains too many contents, it also uses several blank characters at the beginning of the line for line breaks.

Tasks:-name: make sure apache is running service: name = httpd state = running

Among many modules, only the command and shell modules need to be given a list without the "key = value" format. For example:

Tasks:-name: disable selinux command:/sbin/setenforce 0

If the exit code of a command or script is not zero, use the following method:

Tasks:-name: run this command and ignore the result shell:/usr/bin/somecommand |/bin/true

You can also use ignore_errors to ignore the error message:

Tasks:-name: run this command and ignore the result shell:/usr/bin/somecommand ignore_errors: True

3. handlers

It is used to take certain actions when the following resources change.

The action "Y" can be used to be triggered at the end of each play, so as to avoid executing the specified operation every time when multiple changes occur. Instead, the specified operation is performed only once after all changes are completed. The operations listed in handler Y are called handler, that is, the operations defined in handler Y are called.

-Name: template configuration file template: src = template. j2 dest =/etc/foo. conf restart Y:-restart memcached-restart apache

Handler is a list of tasks. These tasks are not essentially different from the preceding tasks.

Handlers:-name: restart memcached service: name = memcached state = restarted-name: restart apache service: name = apache state = restarted

V. playbook case

1. heartbeat. yaml

Heartbeat. yaml-hosts: hbhosts remote_user: root tasks:-name: ensure heartbeat latest version yum: name = heartbeat state = present-name: authkeys configure file copy: src =/root/hb_conf/authkeys dest =/etc/ha. d/authkeys-name: authkeys mode 600 file: path =/etc/ha. d/authkeys mode = 600 running y:-restart heartbeat-name: ha. cf configure file copy: src =/root/hb_conf/ha. cf dest =/etc/ha. d/ha. cf Y:-restart heartbeat handlers:-name: restart heartbeat service: name = heartbeat state = restarted

2. corosync. yaml

-Hosts: hanodes # specifies the host for which the task is to be executed. The host group remote_user: root can be separated by a colon. # specify the user vars who executes the task on the remote host: # define the following two variables: crmsh: crmsh-1.2.6.4.el6.x86_64.rpm pssh: pssh-2.3.1-2.el6.x86_64.rpm tasks: # specifies the list of tasks to be executed, each of which has its name and the module used and the parameter-name: test connection ping: # The ping module does not need to execute the parameter remote_user: jason # specify sudo: yes for the user who runs the task on the remote host in the task # use sudo to execute the task-name: corosync installing yum: name = corosync state = present-name: pacemaker installing # define a software installation task yum: name = pacemaker state = present # install with yum and configure the name of the software to be installed ), and status (state)-name: crmsh rpm packages copy: src =/ansible/corosync/packages/{crmsh} dest =/tmp/{crmsh}-name: pssh rpm packages copy: src =/ansible/corosync/packages/{pssh} dest =/tmp/{pssh}-name: crmsh installing command: yum-y reinstall/tmp/{crmsh}/tmp/{pssh}-name: authkey configure file copy: src =/ansible/corosync/conf/authkey dest =/etc/corosync/authkey-name: authkey mode 400 # define a file permission Setting task file: path =/etc/corosync/authkey mode = 400 notify: # defines a notification. When this task is executed, the handler-restart corosync-name: corosync that can stimulate the response. conf configure file copy: src =/ansible/corosync/conf/corosync. conf dest =/etc/corosync. conf tags:-conf notify:-restart corosync-name: ensure the corosync service startup on boot service: name = corosync state = started enabled = yes handlers: # define the operation to be taken when the following resources change-name: restart corosync # define a service restart task service: name = corosync state = restarted


This article is from the "nmshuishui blog", please be sure to keep this source http://nmshuishui.blog.51cto.com/1850554/1573941

Initial use of ansible and introduction to YAML syntax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.