Automated Operation Dimension Tool Ansible Tutorial _ server Other

Source: Internet
Author: User
Tags stdin vars ssh ansible tutorial saltstack

Introduction of Ansible

1.ansible

Ansible is a new automated operational tools, based on Python research and development. Combines the advantages of many old operational tools to achieve the bulk operating system configuration, batch program deployment, batch operation commands and other functions. Only the Ansible program is installed on the management station to configure the IP information of the managed host, and the managed host has no client. Ansible applications exist in Epel (third-party community) sources and rely on many Python components. Mainly include:

(1), connect the plug-in connection plugins: responsible for and be monitored to achieve communication;

(2), host Inventory: Specifies the operation of the host, is a configuration file inside the definition of monitoring host;

(3), all kinds of module core module, command module, custom module;

(4), with the help of Plug-ins to complete log mail and other functions;

(5), playbook: When a script performs multiple tasks, it is not necessary to allow the node to run multiple tasks at once.

Reference site: http://www.ansible.com.cn

2.ansible Features

Modular design, call specific modules to complete a specific task, itself is the core components, dapper;

Implementation based on Python language, implemented by Paramiko (one of Python's concurrency-connected SSH host functions), Pyyaml and JINJA2 (templating) three key modules;

Simple deployment, agentless without client tools;

Master-slave mode work;

Support custom module function;

Support the Playbook script, the continuous task according to successively set order completes;

Expect each command to have a power-like nature:

3.ansible Architecture

Ansible core:ansible own Core module
Host Inventory: Master Library, defining a manageable host list
Connection plugins: Connection plug-in, general default based on SSH protocol connection
Modules:core modules (self-contained module), custom modules (customized module)
Playbooks: Scripts, performing scheduled tasks in the order in which they are programmed

4. Configuration file:

(1) Ansible application's main configuration file:/etc/ansible/ansible.cfg
(2) Host inventory defines the control host:/etc/ansible/hosts

Follow the INI style; the characters in brackets are group names; a host can belong to multiple groups at the same time;

Example:

Copy Code code as follows:

# Ex 1:ungrouped hosts, specify before any groupheaders. Specifies a host that does not belong to any group directly before the head of any group
Green.example.com
Blue.example.com
192.168.100.1
192.168.100.10
# Ex 2: A collection of hosts belonging to the ' webservers ' group; a group of hosts, such as groups defined as ' webservers '
[Webservers]
alpha.example.org
beta.example.org
192.168.1.100
192.168.1.110

Note: The default is to run as root, but the password is entered multiple times based on the SSH connection operation, which allows authentication based on SSH key

Second, ansible application command

1.ansible-doc command: Get the module list, and the module use format;

Copy Code code as follows:

Ansible-doc-l: Get list
Ansible-doc-s module_name: Get the usage information for the specified module

2.ansible command format

Copy Code code as follows:

Ansible

indicates a managed host, represented in a modal form or directly given IP , must be defined in advance in the document; All Set All

[F Forks]

Specifies how many hosts per batch of controls, default to 5 host a batch of times

[M module_name]

What module management operations are used, all operations need to be specified through the module

[-A args]

specify module specific parameters; args generally for Key=value format

Note: The command module's parameters are not kv format, but directly give the order to execute;

Note: The command module's parameters are not kv format, but directly give the order to execute;

Note:

-ipath,--inventory=path: Indicates the use of the host inventory file path;

Common modules (module_name):

1 command: Default module, can be omitted. Operating commands on a remote host

-A ' COMMAND '

Note: The parameters of the Comand module are not key=value format, directly give the command to be executed

[Root@localhost ~]# ansible all-m command-a ' ifconfig '

2) User:
-A ' name= state={present (create) |absent (delete)} force= (whether to force action to delete home directory) system= uid= the shell= '
[Root@localhost ~]# ansible all-m user-a ' name=ansible state=present '

3) Group:
-A ' name= state={present|absent} gid= system= (System Group) '
[Root@localhost ~]# ansible all-m group-a ' Name=mygroup state=presentsystem=true '

4) Cron:
-A ' name= state= minute= hour= day= month= weekday= '
[Root@localhost ~]# ansible all-m cron-a ' name= ' time ' state=presentminute= ' */5 job= '/usr/sbin/ntpdate ' 172.168.0.1 ' ;>/dev/null '

5) Ping:

No parameters

[Root@localhost ~]# ansible all-m Ping

6) File: Document management
-A ' path= mode= owner= group= state={file|directory|link|hard|touch|absent} src= (link, links to where) '
[Root@localhost ~]# ansible all-m file-a ' path=/tmp/testdirstate=directory '
[Root@localhost ~]# ansible all-m file-a ' path=/tmp/test.txt state=touchmod=600 ' owner=user1 '

7) Copy:

-A ' dest= (remote host path) src= (local host path) content= (directly indicating content) owner= group= mode= '
[root@localhosttmp]# ansible web-m copy-a ' src=/etc/yum.repos.d/aliyun.repodest=/etc/yum.repos.d/'

8) Template

-A ' dest= src=\ ' #\ ' content= owner= group= '

9) Yum:

-A ' name= conf_file= (indicates configuration file) state={present|latest|absent} enablerepo= disablerepo= '
[Root@localhost ~]# ansible all-m yum ' name=httpd state=present '

) Service:

-A ' name= state={started|stopped|restarted} enabled= (boot automatically) runlevel= '
[Root@localhost ~]# ansible all-m service-a ' name=httpd state=started '

One) Shell:

-A ' command ' to run the shell command
[Root@localhost ~]# ansible all-m shell-a echo ' 123456789 ' |passwd--stdin ' user1 '

Script:

-A '/path/to/script ' run script
[Root@localhost ~]# ansible all-m script-a '/tmp/a.sh '

Setup: Gets the facts variable for the specified host;

Iii. playbooks Script

1.playbook Organization format: YAML language format

Playbooks is a more powerful ansible configuration management component that implements multiple tasks based on text file choreography and repeats repeatedly

(1) YAML Introduction

Yaml:yaml Ain ' t Markup Language; Yet Another Markup Language;

Similar to semi-structured data, declarative configuration, more readable format for expressing data sequences, easy to interact with scripting languages
Official site: http://www.yaml.org

(2) syntax format

1 Any secretary structure is indented to identify, you can nest
2 Each row is a key value data key:value, separated by a colon. If you want to identify a line with {} and, separate formatting
3 List Use-logo

2.inventory Parameters: Host Library SSH parameter settings

Ansible based on the remote host specified in the SSH connection inventory, the attributes specified in this parameter are performed;

Ansible_ssh_port

Specify SSH Port

Ansible_ssh_user

Specify SSH User

Ansible_ssh_pass

Specify SSH User login is authentication password, plaintext password is not secure

Ansible_sudo_pass

indicates sudo when the password

Instance:

[Websrvs]

192.168.0.101 ansible_ssh_port=22 Ansible_ssh_user=root ansible_ssh_pass=xuding
192.168.0.102

Note: In the/etc/ansible/hosts directly define the connection time password is not safe, general recommendation based on SSH key authentication way realizes

3.playbooks

(1) Core elements

Tasks tasks, variables variables, templates templates, handlers processors, roles roles

(2) Define tasks in Playbooks:

-Name:task Description Annotation Description information
Module_name:module_args declaration module: defining ansible Module parameters


(3) Ansible-playbook execution order:

Ansible-playbook <filename.yml> ... [Options]


4.playbook---variable

(1) Variable naming: Letters, numbers and underscores, can only start with a letter;

(2) Variable type:

1) Facts: The host-specific attribute information sent back by the remote host, which is stored in the ansible variable, and can be invoked directly without declaration;

2 Custom variables:
Passing through the command line: Ansible-playbook test.yml--extra-vars "Host=www user=test"
Passing through roles

3 Host variables: Variables that are defined after the host in inventory; variables passed directly to a single host

Instance:

Copy Code code as follows:

[root@localhost ~]# vim/etc/ansible/hosts directly defined after the host
[web]
192.168.0.101 Host=mail
192.168.0.102
192.168.0.103

4 Group variable: A variable defined on a group in inventory (for example, edit on the default file/etc/ansible/hosts)

Copy Code code as follows:

[Group_name:vars]
Var1=value
Var2=value

Note: The group name must exist beforehand, and the instance is as follows:

Copy Code code as follows:

[Websrvs]
192.168.0.101
192.168.0.102
[Websrvs:vars]
Host=mail

Variable usage Examples:

Copy Code code as follows:

[root@localhost~]# Vim Useradd.yml
-Hosts:websrvs
Remote_user:root
VARs
Username:testuser
Password:xuding
Tasks
-name:add User
user:name={{Username}} state=present
-name:set Password
Shell:/bin/echo {{password}}} |/usr/bin/passwd--stdin {{username}}

Comments:

1) {{}} call variable
2) #ansible-playbook/path/to/some_yaml_file {-evars|--extra-vars=vars} variable's re-assignment invocation method

Copy Code code as follows:

[Root@localhost ~]# ansible-playbookuseradd.yml--extra-vars "Username=ubuntu"

5.playbook---Tasks

(1) Condition test:

Add a When clause after a task to implement the conditional test function; When statement supports JINJA2 syntax;
Instance: Yum installation was invoked at the time of the Redhat series system

Tasks

Copy Code code as follows:

-name:install Web Server Package
YUM:NAME=HTTPD state=present
when:ansible_os_family = "RedHat"

(2) Iteration: item

Call the built-in item variable in a task, and use the With_items statement to define the list of elements after a task;

Tasks

Copy Code code as follows:

-name:add Four users
user:name={{Item}} state=present
With_items:
-testuser1
-testuser2
-testuser3
-testuser4

Note: In an iteration, each element in a list can be in a dictionary format;

Instance:

Copy Code code as follows:

-name:add two users
user:name={{Item.name}} state=present groups={{item.groups}}
With_items:
-{name: ' Testuser5 ', Groups: ' Wheel '}
-{name: ' Testuser6 ', groups: ' Root '}

6.playbook---Handlers: processor; triggers

The task is triggered only when the conditions of concern are met;
Instance: Configuration file changes triggering restart service

Copy Code code as follows:

-hosts:websrvs
Remote_user:root
Tasks
-name:install httpd
YUM:NAME=HTTPD state=present
-name:install config file
Copy:src=/root/httpd.confdest=/etc/httpd/conf/httpd.conf
Notify:restart httpd
-name:start httpd Service
SERVICE:NAME=HTTPD state=started
Handlers:
-name:restart httpd
SERVICE:NAME=HTTPD state=restarted

7.playbook templates

Templates
Used to generate a text file (a configuration file), a JINJA2 expression can be used in a template file, an expression is defined in {{}}, or a variable substitution can be performed simply;

Roles

Copy Code code as follows:

Roles is used to implement "code reuse";
Roles playbook elements organized in a specific hierarchical format (variables,tasks, templates, handlers);
Can be called directly by the name of role playbook;
Usage: Create [group_name] subdirectories under roles/, not all to be created; for example:
/etc/ansible/roles/(roles directory defined in/etc/ansible/ansible.cfg)
webserver/
Files/: All files used in this role are placed in this directory;
Templates/:jinja2 template file storage location;
tasks/: Task list file; There can be multiple, but at least one file called main.yml;
handlers/: Processor list file; There can be multiple, but at least one file called main.yml;
vars/: variable dictionary file; There can be multiple, but at least one file called main.yml;
meta/: The special settings and dependencies of this role;

Comparison between Ansible and Saltstack

Some time ago used saltstack, should not have to talk about their advantages and disadvantages. Both are very convenient to install and use batch management software.

1, salt to install agent;ansible do not need, through SSH connection, dispense with the agent.

2, salt on the server side to start the process; ansible doesn't need to, but it doesn't matter.

3, salt and ansible have modules, you can use any language development module.

4, salt and ansible all use the Yaml language format to write the script.

Ansible because of the SSH, so it has the process of authentication, as well as the process of password, which makes ansible very slow, does not apply to the large-scale environment (thousands of units).

Why I give up the salt, first the server is not many (hundred), secondly, the salt of the master and the Minion end of the TCP connection is often disconnected, resulting in sometimes the execution of the command will leak the machine, this is just unbearable. I heard that the latest version of the salt a lot better, but because the company system is customized, installation software is particularly troublesome (15M system, to solve the dependency is a big problem), I chose the ansible.

The above is a small set to introduce the automated operation of the tools ansible use of detailed tutorials, I hope to help you.

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.