Detailed explanation of Ansible configuration, host list, and Ansible script playbook

Ansible configuration

configuration file

Ansible is a powerful automation tool that can manage and operate remote hosts. The following is a detailed explanation of the Ansible configuration file.

Ansible's configuration file is ansible.cfg, by default it will be looked for in the following path:

  • in the current working directoryansible.cfg
  • in the user's home directory.ansible.cfg
  • /etc/ansible/ansible.cfg

-cIf you need to use a different file name or path, you can override the default configuration by specifying parameters on the command line .

The following are Ansible's commonly used configuration file parameters and their meanings:

  1. inventory: Specifies the path to the host manifest file, the default is /etc/ansible/hosts.
inventory = /etc/ansible/hosts
  1. library: Used to specify the path of a custom module.
library = /usr/share/my_modules/
  1. remote_tmp: Specifies the directory path on the remote host used to store temporary files.
remote_tmp = ~/.ansible/tmp
  1. local_tmp: Specifies the directory path on the local host used to store temporary files.
local_tmp = ~/.ansible/tmp
  1. remote_user: Specifies the username used by Ansible when executing tasks on the remote host. By default, Ansible uses the username of the currently logged in user.
remote_user = root
  1. private_key_file: Specify the private key file path used by Ansible when executing tasks on the remote host. You can use an SSH key pair for authentication.
private_key_file = /path/to/file
  1. host_key_checking: Specifies whether to check the remote host's SSH host key. By default, this parameter value is true, which means checking the host key; it can be modified to Falseturn off host key checking.
host_key_checking = False
  1. forks: Specifies the number of processes Ansible uses when executing tasks simultaneously. By default, this parameter value is 5.
forks          = 5
  1. becomeand become_method: used to perform tasks as an administrator on the remote host. becomeThe parameter is used to specify whether to enable the administrator to perform tasks, and it can be set to trueor false; become_methodthe parameter is used to specify the way to obtain the administrator's identity, and the commonly used values ​​include sudo, , suand so on.
become=True
become_method=sudo
  1. log_path: Specify the log file path of Ansible. You can view Ansible's execution logs and error messages in this file.
log_path = /var/log/ansible.log

host list

Ansible host inventory (Inventory) refers to the host list used by Ansible to manage and perform tasks. The host list can be a text file or a script or program. In the host list, each host has a unique name and one or more variables, which are used to specify the host's connection parameters, host group, host status and other information.

Inventory configuration file

/etc/ansible/hosts

Modify the location of the Inventory file in the configuration file. As mentioned above, the default location is/etc/ansible/ansible.cfg

If you want to modify to /opt/ansible/hosts, you need to modify the configuration file

inventory = /opt/ansible/hosts

-iPass host inventory configuration file using parameters

[root@localhost ~]# ansible-playbook -i /opt/ansible/hosts xxx.yaml

Grouping of remote hosts

Group remote hosts for use in playbooks. The following file shows the simplest grouping method in the host list file. [ ] is the group name. Divide the remote host into several groups: test1, test2, test3

vim /etc/ansible/ansible.cfg
# 添加如下
192.168.100.10

[test1]
192.168.200.10
192.168.200.20
three.ipipip.com

[test2]
192.168.200.40
192.168.200.50

[test3]
192.168.200.60

Grouping can also support nesting. For example [new_york], [california], [texas]etc. Then, we can use [usa:children]to group these subgroups together and manage them as a whole.

[new_york]
192.168.200.20
192.168.100.30

[california]
192.168.200.40
192.168.100.10

[texas]
192.168.100.20

[test3]
192.168.200.60

[usa:children]
new_york
california
texas

variable

Variables in the host manifest file

Specify parameters for a single remote host

[test1]
192.168.100.10   http_port=80  
192.168.100.20   http_port=303 

Specify variables for a group

[test1]
192.168.100.10   
192.168.100.10
[test1:vars]
http_port=80

Ansible script playbook

Playbook file format YAML

Ansible Playbook is written in YAML format. YAML (YAML Ain't Markup Language) is a lightweight data serialization format that is easy to read and write. Here is an example YAML file:

---

- hosts: webservers
  become: yes
  tasks:

  - name: Install Apache2
    apt:
     name: apache2
     state: latest

  - name: Start Apache2
    service:
     name: apache2
     state: started
   
# 该示例中,--- 表示 YAML 文件的开始
# hosts 指定了要管理和配置的主机组
# become 表示以管理员身份执行任务。
# tasks 则包含了一组有序的任务列表,其中包括了安装和启动 Apache 两个任务。
# apt 和 service分别表示使用 apt 命令安装 Apache 和启动 Apache 服务

It should be noted that the indentation and format of the YAML file are very important, as they determine the semantics and structure of the file.

The following are some common YAML syntax:

  1. Comments: YAML files support comment annotations using #the tag

  2. Key-value pairs: In YAML files, key-value pairs are :separated by colons, and spaces are used for indentation between keys and values. For example:

key: value
  1. array list
- item1
- item2
- item3

Each element in the array -starts with

  1. Things to note

When there is a colon (:) in the variable, add quotes

foo: "ansibleLinuxdocker:i like"

{ Use quotes when variables begin with

foo: "{
    
    {chenshiren}}"

ansible-playbook commands

How to execute Ansible script Playbook? Ansible provides a separate command: ansible-playbook

Common ways to use ansible-playbook are as follows:

Basic methods of executing Playbook

ansible-playbook playbook.yml
# playbook.yml 是要执行的 Ansible Playbook 文件名

Detecting the syntax of a script using --syntax-checkparameters

ansible-playbook  playbook.yml --syntax-check

Use --verboseto view output details

ansible-playbook playbook.yml --verbose

Use --list-hoststo see which hosts the script affects

ansible-playbook playbook.yml --list-hosts

Execute scripts in parallel

ansible-playbook playbook.yml -f 10

Basic syntax of Playbook

Take the yaml script shown above as an example

---

- hosts: webservers
  become: yes
  tasks:

  - name: Install Apache2
    apt:
     name: apache2
     state: latest

  - name: Start Apache2
    service:
     name: apache2
     state: started

can be divided into two parts

  1. On what machine and with what identity?
- hosts: webservers
  become: yes
key meaning
hosts It is the IP of the host, or the host group name, or the keyword all
remote_user Which user to execute remotely as
become Switch to execute as another user, the value is yes or no
become_method Used together with become, it means it can be 'sudo'/'su', etc.
become_user Used with become_user, which can be root or other username
  1. What tasks are performed?
  - name: Install Apache2
    apt:
     name: apache2
     state: latest

  - name: Start Apache2
    service:
     name: apache2
     state: started
  • Tasks are executed sequentially from top to bottom. If an error occurs in the middle, the entire Playbook will be suspended.

  • Each task is a call to the module, just with different parameters and variables.

  • It is best for each task to have a name attribute, which is for human reading and has no actual operation. Then it will be output in the command line to prompt the user about the execution status.

Basic syntax for tasks

 tasks:
  - name: Install Apache2
    apt:
     name: apache2
     state: latest

The name is optional and can also be abbreviated as follows

 tasks:
  - apt:
     name: apache2
     state: latest

When a task with a written name is executed in Playbook, the corresponding name will be displayed, making the information more friendly and rich.

as follows

TASK [install http]   *********************************************************************
changed: [192.168.200.20]
changed: [192.168.200.30]

When a task without a name is executed in Playbook, the corresponding task syntax is directly displayed. If there are many calling modules, it is easy to lose track of where to run it.

TASK [yum: name=httpd state=present] *********************************************************************
changed: [192.168.200.20]
changed: [192.168.200.30]

Different ways of writing parameters

Method 1

 tasks:
  - name: Install Apache2
    apt: name=apache2 state=latest

Method 2

When the parameters that need to be passed in are too long, they can be separated into multiple lines.

  tasks:
  - name: 设置文件权限  
    copy: src=/home/csq.txt  dest=/tmp/csq.txt
           owner=csq  group=csq  mode=0644

Method 3
or use YML field format to pass in parameters

 tasks:
  - name: Install Apache2
    apt:
     name: apache2
     state: latest

Task execution status

  • If executed this time, the Action will get the return valuechanged

  • If execution is not required, the Action will get the return valueok

# 以这个文件内容为例执行两次看看结果
- hosts: server
  tasks:
  - name: 复制文件
    copy:
     src: /etc/sudoers
     dest: /opt/

Execute first time

image-20230601202326290

Execute second time

image-20230601202355665

Since the file has already been copied during the first execution, Ansible will avoid repeated copying based on the status of the target file.

variable

User-defined variables in Playbook

varsUsers can customize variables through keywords in Playbook , and use { {}} to quote them.

For example

[root@localhost ceshi]# vim ansible.yaml 
- hosts: server
  vars:
   stdin: "hello,word"
  tasks:
  - name: 输出hello,word
    command: echo {
    
    {
    
    stdin}}

Put variables in separate files

In Ansible, when there are many variables or need to be reused in multiple Playbooks, the variables can be placed in a separate file, and then the var_filesvariables defined in this file can be referenced by keywords in the Playbook. For example, we can vars.ymldefine some variables in the file

For example, we can vars.ymldefine some variables in the file:

[root@localhost ceshi]# mkdir vars
[root@localhost ceshi]# vim vars/vars.yaml 
#定义数据库的连接信息
files: /home/csq/csq.txt

Then, use in the Playbook var_filesto reference these variables:

[root@localhost ceshi]# vim ansible.yaml 
---

- hosts: server
  vars_files:
   - vars/vars.yaml
  tasks:
  - name: 创建两个文件 /home/csq/csq.txt /home/zhw/zhw.txt
    file:
     path: "{
    
    {files}}"
     state: touch
     mode: 0600

Variables used in file templates

In Ansible, templatethe module is used to render the local Jinja2 template file and then write the result to a file on the remote host. In templatea module, you can use a variety of methods to pass variables that need to be used in the template file. Here are a few common ways:

Use varsparameters to pass variables

You can templateuse varsparameters in modules to pass variables.

For example:

[root@localhost ceshi]# vim ansible.yaml 
---

- hosts: test1
  vars:
   defined_name: "Hello My name is Chenshiren"
   ansible_hostname: chenshiren
   ansible_default_ipv4: 192.168.200.10
  remote_user: root
  tasks:
  - name: 安装http
    yum:
     name: httpd
     state: present
  - name: 写入配置文件http.conf
    template:
     src: templates/httpd.conf.j2
     dest: /etc/httpd/conf/httpd.conf
  - name: 写入html文件
    template:
     src: templates/index.html.j2
     dest: /var/www/html/index.html
  - name: 重启http服务 设置开机自启
    service:
     name: httpd
     state: restarted
     enabled: yes
# 执行过程
[root@localhost ceshi]# ansible-playbook ansible.yaml 

PLAY [test1] ****************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [192.168.200.30]

TASK [安装http] ***************************************************************************
ok: [192.168.200.30]

TASK [写入配置文件http.conf] ******************************************************************
ok: [192.168.200.30]

TASK [写入html文件] *************************************************************************
changed: [192.168.200.30]

TASK [重启http服务] *************************************************************************
changed: [192.168.200.30]

PLAY RECAP ******************************************************************************
192.168.200.30             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
# 执行完成以后关闭一下防火墙

image-20230602125845774

The contents of the index.html.j2 file are as follows

[root@localhost ceshi]# cat templates/index.html.j2 
<html>
<title>Demo</title>
<body>
<div class="block" style="hight:99%;">
  <div class="centered">
    <h1>#46 Demo {
    
    {defined_name}} <h1>
      <p>Served by {
    
    {
    
    ansible_hostname}} ({
    
    {
    
     ansible_default_ipv4}}).</p>
  </div>
</div>
</body>
</html>
# 你只需要知道 {
    
    {}} 是用来引用变量的就行了

Guess you like

Origin blog.csdn.net/qq_52089863/article/details/131004896