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.
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
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
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
用于当关注的资源发生变化时采取一定的操作。
“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
tags用于让用户选择运行或略过playbook中的部分代码。ansible具有幂等性因此会自动跳过没有变化的部分即便如此有些代码为测试其确实没有发生变化的时间依然会非常地长。
此时如果确信其没有变化就可以通过tags跳过此些代码片断。
下面再给出一个安装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!


For years, Linux software distribution relied on native formats like DEB and RPM, deeply ingrained in each distribution's ecosystem. However, Flatpak and Snap have emerged, promising a universal approach to application packaging. This article exami

The differences between Linux and Windows in handling device drivers are mainly reflected in the flexibility of driver management and the development environment. 1. Linux adopts a modular design, and the driver can be loaded and uninstalled dynamically. Developers need to have an in-depth understanding of the kernel mechanism. 2. Windows relies on the Microsoft ecosystem, and the driver needs to be developed through WDK and signed and certified. The development is relatively complex but ensures the stability and security of the system.

The security models of Linux and Windows each have their own advantages. Linux provides flexibility and customizability, enabling security through user permissions, file system permissions, and SELinux/AppArmor. Windows focuses on user-friendliness and relies on WindowsDefender, UAC, firewall and BitLocker to ensure security.

Linux and Windows differ in hardware compatibility: Windows has extensive driver support, and Linux depends on the community and vendors. To solve Linux compatibility problems, you can manually compile drivers, such as cloning RTL8188EU driver repository, compiling and installing; Windows users need to manage drivers to optimize performance.

The main differences between Linux and Windows in virtualization support are: 1) Linux provides KVM and Xen, with outstanding performance and flexibility, suitable for high customization environments; 2) Windows supports virtualization through Hyper-V, with a friendly interface, and is closely integrated with the Microsoft ecosystem, suitable for enterprises that rely on Microsoft software.

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!
