Home >System Tutorial >LINUX >Ansible usage: simple use of ansible-playbook

Ansible usage: simple use of ansible-playbook

WBOY
WBOYOriginal
2024-09-02 14:55:041170browse

Ansible usage: simple use of ansible-playbook

ansbile-playbook is a collection of system ansible commands, which is written in the yaml language and runs the process. The ansbile-playbook commands are executed in top-down order. At the same time, playbook has created many features. It allows you to transfer the status of a certain command to a subsequent command. For example, you can grab content from a file on one machine and attach it as a variable, and then use it on another machine. This allows you to implement some complex deployment mechanisms that are not possible with ansible commands.

Playbook is used through the ansible-playbook command. Its parameters are similar to the ansible command, such as the parameters -k (–ask-pass) and -K (–ask-sudo) to ask for the ssh password and sudo password, and -u to specify the user. ,These instructions can also be written in the playbook through ,prescribed units. Simple usage of ansible-playbook: ansible-playbook example-play.yml.

1. A simple example

A simple ansible-playbook example is given below to understand its composition.

# cat user.yml
- name: create user
hosts: all
user: root
gather_facts: false
vars:
- user: "test"
tasks:
- name: create user
user: name="{{ user }}"

The function implemented by the playbook above is to add a new user:

The name parameter provides an overview of the functions implemented by the playbook. During subsequent execution, the value of the name variable will be printed;

The hosts parameter specifies which hosts to participate in;

The user parameter specifies the user to use to log in to the remote host;

The gather_facts parameter specifies whether to execute the setup module to obtain host-related information before the following tasks are executed. This will be used when subsequent tasks will use the information obtained by the setup;

The vars parameter specifies a variable. Here it refers to a user variable whose value is test. It should be noted that the variable value must be enclosed in quotation marks;

task specifies a task, and the name parameter below it is also a description of the task, which will be printed out during execution. User specifies calling the user module, name is a parameter in the user module, and the added user name calls the value of the user variable above. The specific execution results are as follows:

[root@361way playbooks]# ansible-playbook user.yml
PLAY [create user] ************************************************************
TASK: [create user ] **********************************************
changed: [10.212.52.252]
changed: [10.212.52.14]
changed: [10.212.52.16]
PLAY RECAP ********************************************************************
10.212.52.14 : ok=1 changed=1 unreachable=0 failed=0
10.212.52.16 : ok=1 changed=1 unreachable=0 failed=0
10.212.52.252 : ok=1 changed=1 unreachable=0 failed=0

Similarly, if you want to delete this newly added user, you only need to replace the last line of the playbook file with the following line and then execute the corresponding playbook:

user: name="{{ user }}" state=absent remove=yes
2. One-click patching bash shellcode example

Give us a slightly more complicated example, using ansible-playbook to simultaneously patch bash shellcode vulnerabilities on N hosts. It should be noted that there may be different system versions distributed among the hosts on the existing network. It is assumed here that both centos5 and 6 versions exist on the existing network. The specific playbook content is as follows:

# cat update_bash.yml
- hosts: all
remote_user: root
gather_facts: True
tasks:
- name: update bash in redhat 6 version
yum: name=http://mirrors.aliyun.com/centos/6.6/os/x86_64/Packages/bash-4.1.2-29.el6.x86_64.rpm.rpm state=present
when: ansible_os_family == "RedHat" and ansible_distribution_version|int >=6
- name: update bash in redhat 5 version
yum: name=http://mirrors.hustunique.com/centos/5/updates/x86_64/RPMS/bash-3.2-33.el5.1.x86_64.rpm state=present
when: ansible_os_family == "RedHat" and ansible_distribution_version|int 
<p>The when statement is used above, and the gather_facts setup module is also enabled. The ansible_os_family variable and ansible_distribution_version variable here are the information obtained directly from the setup module. </p>
<p>If there are a large number of hosts, just add -f when running and select an appropriate number of concurrent hosts. I used this here and the bash upgrade was completed quickly. </p>
<div style="font-size: 14pt; color: white; background-color: black; border-left: red 10px solid; padding-left: 14px; margin-bottom: 20px; margin-top: 20px;"><strong>3. The composition of playbook</strong></div>
<p>playbook是由一个或多个“play”组成的列表。play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来讲所谓task无非是调用ansible的一个module。将多个play组织在一个playbook中即可以让它们联同起来按事先编排的机制同唱一台大戏。其主要有以下四部分构成</p>
<ol class="linenums">
<li class="L0"><span class="pln">playbooks组成:</span></li>
<li class="L1"><span class="pln"> Target section: 定义将要执行 playbook 的远程主机组</span></li>
<li class="L2"><span class="pln"> Variable section: 定义 playbook 运行时需要使用的变量</span></li>
<li class="L3"><span class="pln"> Task section: 定义将要在远程主机上执行的任务列表</span></li>
<li class="L4"><span class="pln"> Handler section: 定义 task 执行完成以后需要调用的任务</span></li>
</ol>
<p>而其对应的目录层为五个,如下:</p>
<ol class="linenums">
<li class="L0"><span class="pln">一般所需的目录层有:(视情况可变化)</span></li>
<li class="L1"><span class="pln"> vars 变量层</span></li>
<li class="L2"><span class="pln"> tasks 任务层</span></li>
<li class="L3"><span class="pln"> handlers 触发条件</span></li>
<li class="L4"><span class="pln"> files 文件</span></li>
<li class="L5"><span class="pln"> template 模板</span></li>
</ol>
<p>下面介绍下构成playbook 的四层结构。</p>
<div style="margin-top: 2em; margin-bottom: 1em;"><span style="color: #1e1e1e; letter-spacing: 2px; border-left: #FF3030 3px solid; border-right: #FF3030 3px solid; padding-left: 8px; padding-right: 8px; font-size: 12pt;"><strong>1、Hosts和Users</strong></span></div>
<p>playbook中的每一个play的目的都是为了让某个或某些主机以某个指定的用户身份执行任务。</p>
<p>hosts 用于指定要执行指定任务的主机其可以是一个或多个由冒号分隔主机组。</p>
<p>remote_user 则用于指定远程主机上的执行任务的用户。<br>
不过remote_user也可用于各task中。也可以通过指定其通过sudo的方式在远程主机上执行任务其可用于play全局或某任务。<br>
此外甚至可以在sudo时使用sudo_user指定sudo时切换的用户。</p>
<p>示例:</p>
<pre class="brush:php;toolbar:false">- hosts: webnodes
tasks:
- name: test ping connection:
remote_user: test
sudo: yes
2、任务列表和action

play的主体部分是task list。

task list中的各任务按次序逐个在hosts中指定的所有主机上执行即在所有主机上完成第一个任务后再开始第二个。在运行自下而下某playbook时如果中途发生错误所有已执行任务都将回滚因此在更正playbook后重新执行一次即可。

task的目的是使用指定的参数执行模块而在模块参数中可以使用变量。模块执行是幂等的这意味着多次执行是安全的因为其结果均一致。每个task都应该有其name用于playbook的执行结果输出建议其内容尽可能清晰地描述任务执行步骤。如果未提供name则action的结果将用于输出。

定义task的可以使用“action: module options”或“module: options”的格式推荐使用后者以实现向后兼容。如果action一行的内容过多也中使用在行首使用几个空白字符进行换行。

tasks:
- name: make sure apache is running
service: name=httpd state=running
在众多模块中只有command和shell模块仅需要给定一个列表而无需使用“key=value”格式例如
tasks:
- name: disable selinux
command: /sbin/setenforce 0 如果命令或脚本的退出码不为零可以使用如下方式替代
tasks:
- name: run this command and ignore the result
shell: /usr/bin/somecommand || /bin/true
或者使用ignore_errors来忽略错误信息
tasks:
- name: run this command and ignore the result
shell: /usr/bin/somecommand
ignore_errors: True
3、handlers

用于当关注的资源发生变化时采取一定的操作。
“notify”这个action可用于在每个play的最后被触发这样可以避免多次有改变发生时每次都执行指定的操作取而代之仅在所有的变化发生完成后一次性地执行指定操作。
在notify中列出的操作称为handler也即notify中调用 handler中定义的操作。

注意:在 notify 中定义内容一定要和tasks中定义的 - name 内容一样,这样才能达到触发的效果,否则会不生效。

- name: template configuration file
template: src=template.j2 dest=/etc/foo.conf
notify:
- restart memcached
- restart apache
handler是task列表这些task与前述的task并没有本质上的不同。
handlers:
- name: restart memcached
service: name=memcached state=restarted
- name: restart apache
service: name=apache state=restarted
4、tags

tags用于让用户选择运行或略过playbook中的部分代码。ansible具有幂等性因此会自动跳过没有变化的部分即便如此有些代码为测试其确实没有发生变化的时间依然会非常地长。
此时如果确信其没有变化就可以通过tags跳过此些代码片断。

5、示例

下面再给出一个安装httpd web服务的示例:

# cat /etc/ansible/playbook/install_web.yml
- hosts: webservers
remote_user: root
gather_fasks: False
vars:
packages: httpd
tasks:
- name: Install httpd
yum: name={{ packages }} state=present
- name: Cofiguration httpd
copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
tags: httpd_conf
notify:
- restart httpd
- name: Start httpd
service: name=httpd state=started enabled=no
tags: start
- name:Add centos user
user: name={{ item }} state=absent
tags: adduser
with_items:
- centos
- admin
handlers:
- name: restart httpd
service: name=httpd state=restart

注:上面的代码没有考虑ubuntu平台,仅仅考虑centos/redhat平台。

The above is the detailed content of Ansible usage: simple use of ansible-playbook. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn