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

How to use ansible

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

How to use ansible? for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

1.ansible

Ansible is a new automatic operation and maintenance tool based on Python. It combines the advantages of many established operation and maintenance tools to realize the functions of batch operating system configuration, batch program deployment, batch running commands and so on. Only need to install the ansible program on the management workstation to configure the IP information of the controlled host, and the controlled host has no client. Ansible applications exist in epel (third-party community) sources and depend on many python components

2.ansible characteristics

Modular design, calling specific modules to complete specific tasks, itself is the core component, short and pithy

Based on Python language, it is implemented by three key modules: Paramiko (a concurrently connectable ssh host function library of python), PyYAML and Jinja2 (templating).

Simple deployment, agentless clientless tools

Master-slave mode work

Support custom module function

Playbook scripts are supported, and consecutive tasks are completed in order of setting.

Each command is expected to be idempotent:

3.ansible architecture

Ansible core:ansible 's own core module

Host inventory: host library that defines the list of hosts that can be controlled

Connection plugins: connection plug-in, which is generally connected based on ssh protocol by default

Modules:core modules (built-in module), custom modules (custom module)

Playbooks: a script that performs scheduled tasks in the order in which they are arranged.

4. Configuration file:

(1) main configuration file of ansible application: / etc/ansible/ansible.cfg

(2) Host Inventory defines the control host: / etc/ansible/hosts

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

Example:

# Ex 1: Ungrouped hosts, specify before any groupheaders. A host that is specified directly in front of the header of any group and does not belong to 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 batch of hosts belong to a group, such as a group defined as' webservers'

[webservers]

Alpha.example.org

Beta.example.org

192.168.1.100

192.168.1.110

Note: root users are used by default, but the password is entered multiple times for connection operations based on ssh. For convenience, authentication based on ssh keys can be used.

II. Ansible application commands

1.ansible-doc command: get the list of modules and the format in which they are used

Ansible-doc-l: get list

Ansible-doc-s module_name: gets the usage information of the specified module

2.ansible command format

Ansible [- f forks] [- m module_name] [- an args]

Indicates that the control host, represented in mode or directly given IP, must be defined in advance in the file; all sets all

[- f forks]

Indicates how many hosts are controlled in each batch. The default is 5 hosts in a batch.

[- m module_name]

Which module is used to manage operations, all operations need to be specified through the module

[- an args]

Indicates the module-specific parameters; args is generally in key=value format

Note: the parameters of the command module are not in kv format, but simply give the command to be executed.

Note: read / etc/ansible/hosts by default, and you can also specify the custom file path.

-iPATH,-- inventory=PATH: indicates the path of the host inventory file used

Common modules (module_name):

1) command: default module, which can be omitted. Perform operation commands on the remote host

-a 'COMMAND'

Note: the parameters of the comand module are not in key=value format, and the commands to be executed are given directly.

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

2) user:

-a roomname = state= {present (create) | absent (delete)} force= (whether to force operation to delete home directory) system= uid= shell=home='

[root@localhost] # ansible all-m user-a 'name=ansible state=present'

3) group:

-a present state = {present | absent} state (system group)'

[root@localhost] # ansible all-m group-a 'name=mygroup state=presentsystem=true'

4) cron:

-a 'name=state= minute= hour=day= month= weekday=job='

[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 parameter

[root@localhost] # ansible all-m ping

6) file: file management

-a path = mode= owner=group=state= {file | directory | link | hard | touch | absent} src= (link, where to link)'

[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 destination = (path on remote host) src= (local host path) content= (direct 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= mode='

9) yum:

-a roomname = conf_file= (indicates the configuration file) state= {present | latest | absent} enablerepo=disablerepo='

[root@localhost ~] # ansible all-m yum 'name=httpd state=present'

10) service:

-a started state = {started | stopped | restarted} enabled= (whether to boot automatically) runlevel='

[root@localhost] # ansible all-m service-a 'name=httpd state=started'

11) shell:

-run the shell command by running the command

[root@localhost ~] # ansible all-m shell-an echo "123456789" | passwd-- stdin user1'

12) script:

-a script to run the script to match the path

[root@localhost] # ansible all-m script-a'/ tmp/a.sh'

13) setup: gets the facts variable of the specified host

III. Playbooks script

1.playbook organizational format: Yaml language format

Playbooks is a more powerful configuration management component of ansible, which implements multiple tasks based on text file orchestration and performs repeatedly.

(1) introduction to YAML

YAML:YAML Ain't Markup Language; Yet Another Markup Language

Similar to semi-structured data, declarative configuration; highly readable format used to express data sequences, easy to interact with scripting languages

Official site: http://www.yaml.org

(2) grammatical format

1) any clerical structure is marked with indentation and can be nested

2) each row is a key data key:value, separated by colons. If you want to identify on a line, you need to use {} and separate the format.

3) list is used to identify

2.inventory parameter: host library ssh parameter settin

When ansible connects to a remote host specified in inventory based on ssh, it executes the properties specified by the parameters at this point.

Ansible_ssh_port

Specify ssh port

Ansible_ssh_user

Specify ssh user

Ansible_ssh_pass

Specify that the ssh user login is an authentication password, and the plaintext password is not secure.

Ansible_sudo_pass

Specify the password for sudo

3.playbooks

(1) Core elements

Tasks tasks, Variables variables, Templates templates, Handlers processors, Roles roles

(2) define tasks in playbooks:

-name: task description comment description information

Module_name: module_args declaration module: define ansible module parameters

(3) ansible-playbook executes the command:

Ansible-playbook... [options]

wKioL1a_UZXAMlY-AABkfVb3p2Q769.png

4. Playbook, music, color-variable

(1) variable naming: consists of letters, numbers and underscores, and can only start with a letter

(2) types of variables:

1) facts: host-specific attribute information sent back by a remote host, which is stored in the ansible variable. Without declaration, you can call the

2) Custom variables:

Pass through the command line: ansible-playbook test.yml-- extra-vars "host=www user=test"

Pass through roles

3) Host variable: a variable defined after a host in inventory; a variable passed directly to a single host

Example:

[root@localhost ~] # vim / etc/ansible/hosts is defined directly after the host

[web]

192.168.0.101 host=mail

192.168.0.102

192.168.0.103

4) Group variables: variables defined on groups in inventory (for example, editing on the default file / etc/ansible/hosts)

[group_name:vars]

Var1=value

Var2=value

Note: the group name must exist in advance. The example is as follows:

[websrvs]

192.168.0.101

192.168.0.102

[websrvs:vars]

Host=mail

Examples of using variables:

[root@localhost~] # vimuseradd.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}}

Note:

1) {{}} call variable

2) # ansible-playbook/PATH/TO/SOME_YAML_FILE {- eVARS |-- extra-vars=VARS} variable reassignment calling method

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

5. Playbook, music, tasks.

(1) conditional testing:

The conditional testing function can be realized by adding a when clause after a task; the when statement supports Jinja2 syntax

Example: yum installation is called on RedHat series system at that time

Tasks:

-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 task; use the with_items statement after a task to define the element list

Tasks:

-name: add four users

User: name= {{item}} state=present

With_items:

-testuser1

-testuser2

-testuser3

-testuser4

Note: during iteration, each element in the list can be in dictionary format

Example:

-name: add two users

User: name= {{item.name}} state=presentgroups= {{item.groups}}

With_items:

-{name: 'testuser5', groups:' wheel'}

-{name: 'testuser6', groups:' root'}

6. PlaybookMurray-handlers: processor; trigger

The task will be triggered only when the conditions of its concern are met.

Example: a change in configuration file triggers a restart of the service

-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 template

Templates:

Used to generate text files (configuration files); jinja2 expressions can be used in template files, defined in {{}}, or simply perform variable substitution

Roles:

Roles is used to achieve code reuse.

Playbook elements (variables,tasks, templates, handlers) organized by roles in a specific hierarchical format.

Can be called directly by playbook in the name of role

Usage: create [group_name] subdirectories under roles/, but not all of them need to be created; for example:

/ etc/ansible/roles/ (define the roles directory in / etc/ansible/ansible.cfg)

Webserver/

Files/: all files used in this role are placed in this directory

Location of templates/:Jinja2 template files

Tasks/: task list file; there can be more than one, but at least one file called main.yml

Handlers/: processor list file; there can be more than one, but at least one file called main.yml

Vars/: variable dictionary file; there can be more than one, but at least one file called main.yml

Meta/: special settings and dependencies for this role

This is the answer to the question about how to use ansible. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel to learn more about it.

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

Internet Technology

Wechat

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

12
Report