Ansible installation and simple block usage

Table of contents

I. Overview

2. Installation

1. Select source

2. Install ansible

3. Module view

3. Experiment

1. Topology editing

2. Set up group and ping module

3. hostname module

4. file module

Edit

5. stat module

6. Copy module (copy locally to remote)

7. The fetch module is similar to the copy module, but has the opposite effect. Used to copy files from a remote machine to the local machine.

8. user module

9. group module

10. cron module

4. yum_repository module

5. yum module

6. Server module

7. script module

8. command and shell modules

9. playbook

YMAL format



I. Overview

Ansible is an automation tool used for configuration management, application deployment, and orchestrating cloud deployments. It is an open source tool written in Python that communicates with remote hosts through the SSH protocol.

1. Related introduction and similar platforms:
   - Related introduction: Ansible is an agent-based automation tool that uses simple, lightweight syntax. Its main goal is to make the automation process simple and easy to use, while providing powerful features to manage large-scale infrastructure.
   - Similar platforms: Automation tools similar to Ansible include Puppet, Chef, SaltStack, etc. These tools all provide similar functionality but have slightly different syntax, working principles, and deployment models.

2. Why use Ansible, what it can do, and its advantages:
   - Easy to use: Ansible uses YAML-based syntax, which is easy to understand and write without programming knowledge. It also has good documentation and active community support.
   - Agentless: Ansible uses the SSH protocol to communicate without the need to install any agent on the remote host, which makes deployment and configuration simpler and more secure.
   - Script-based: Ansible uses a script-based approach to describe and execute automated tasks, making task organization and management more flexible and scalable.
   - Highly configurable: Ansible supports various platforms and operating systems, and provides a wealth of modules and plug-ins to manage various types of resources, including servers, network devices, cloud platforms, etc.
   - Extensibility: Ansible has strong extensibility, and custom modules and plug-ins can be written according to specific needs, or integrated with existing tools and systems.

3. How it works:
   - Ansible uses one control node to manage multiple remote hosts. The Ansible configuration file on the control node describes the tasks that need to be performed and related host information.
   - When the control node executes an Ansible command, it connects to the remote host via SSH and performs the corresponding tasks on the remote host.
   - Ansible uses a module-based approach to manage and configure remote hosts. It can perform various operations through built-in modules, such as file management, software package installation, service management, etc.
   - Ansible also supports the use of playbooks to define and organize multiple tasks, as well as the use of variables and conditions to implement more complex automation processes.

Overall, Ansible is a powerful, easy-to-use and agentless automation tool that can help simplify the process of configuration management and application deployment, improve work efficiency and maintainability.

Core components:

•    Inventory:Ansible 管理的主机信息,包括 IP 地址、 SSH 端口、账号、密码 等;

    Modules:任务均有模块完成,也可以自定义模块,例如经常用的脚本;

•    Plugins使用插件增加Ansible 核心功能,自身提供了很多插件, 也可以自

定义插件。例如 connection 插件, 用于连接目标主机。 callback 插件可以将 果输出到其他地方。vars 插件将定义的比变量注入到Ansible 中运行。

•    Playbooks:“剧本”,模块化定义一系列任务,供外部统一调用。Ansible 核心功能。

 Ansible 可以在安装了 Python 2 (版本 2.6 或 2.7)或 Python 3 (版本 3.5 及更高版本) 的任何机器上运行(管理机器不支持 Windows)。

二、安装

在开始实验前我们先同步集群时间、进行ssh免密

##每台主机
ssh-keygen
ssh-copy-id 192.168.115.131
##在192.168.115.131
for i in 136 140 ;do scp /root/.ssh/authorized_keys 192.168.115.$i:/root/.ssh ;done
##同步集群时间
for i in 131 136 140 ;do ssh 192.168.115.$i yum -y install ntp;done
for i in 131 136 140 ;do ssh 192.168.115.$i systemctl restart ntpd;done

1、选择源

cd /etc/yum.repos.d
mkdir back
mv * bcak
yum clean all
yum makecache
yum update
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
curl-o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
yum makecache frist
yum update

2、安装ansible

yum -y install epel-release.noarch
yum -y install ansible

3、模块查看

###模块列表
ansible-doc -l

###模块用法查看
ansible-doc 模块名

三、实验

1、拓扑

2、设置组、ping模块

绿色成功、红色失败

方式1

vim /etc/ansible/hosts
###插入
[group]
192.168.115.131
192.168.115.136
192.168.115.140
###利用模块ping
ansible -m ping group

方式2

#如果主机数量太多就这样表示
[group]
192.168.115.[136:140]

方式3

##指定端口
[group]
192.168.115.136:22

方式4

###别名
[group]
192.168.115.136:22
hy ansible_ssh_host=192.168.115.140 ansible_ssh_port=22

方式5

##没有ssh免密的也可以
[group]
ansible_ssh_host=192.168.115.140 ansible_ssh_port=22 ansible_ssh_user=用户名 ansible_ssh_pass="密码"

方式6

###利用别名分组
[group]
192.168.115.136:22
hy ansible_ssh_host=192.168.115.136 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="123.com"
nginx ansible_ssh_host=192.168.115.140 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="123.com"
[nginx]
nginx
[hy]
hy

3、hostname模块

The basic format is: machine name or group name for ansible operation -m module name -a "parameter 1=value 1 parameter 2=value 2" argment

Yellow indicates success

###修改192.168.115.136的主机名hy
###修改192.168.115.140的主机名nginx
ansible hy -m hostname -a 'name=hy'
ansible nginx -m hostname -a 'name=nginx'

4. file module

1. Create a directory

##创建一个目录
ansible hy -m file -a "path=/opt/hy.txt state=directory"

2. Create files


ansible hy -m file -a "path=/opt/hy.txt/test.tst state=touch"

3. Modify owner group and permissions

####修改属主为hy,属组hy 权限777
ansible hy -m file -a "path=/opt/hy.txt recurse=yes owner=hy group=hy mode=777"

4. Delete the directory (including files in the directory)

###删除/opt/hy.txt
 ansible hy -m file -a "path=/opt/hy.txt state=absent"

5. Create soft and hard connections

#软
ansible hy -m file -a "src=/etc/fstab path=/opt/fstab2 state=link"
#硬
ansible hy -m file -a "src=/etc/fstab path=/opt/fstab1 state=hard"

5. stat module

###用来获取文件的信息状态
ansible hy -m file -a "path=/opt/hy.txt state=touch"
ansible hy -m stat -a "path=/opt/hy.txt"

6. Copy module (copy locally to remote)

Prepare a file to be copied to 2 agents on ansible

 echo 192.168.115.131 > 1.txt
ansible group -m copy -a "src=/root/1.txt dest=/opt"

Use content to remotely write content and overwrite the original content

ansible group -m copy -a "content="hello\n" dest=/opt/1.txt"

Whether to use the force parameter to force coverage

##写入
echo 192.168.115.131 > 1.txt
ansible group -m copy -a "content="hello" dest=/opt/1.txt force=no"#如果目标文件存在,不覆盖
ansible group -m copy -a "content="hello" dest=/opt/1.txt force=yes"#如果目标文件存在,覆盖

Use the backup module to back up local files to the remote end.

###把本机的文件备份到远端
ansible group -m copy -a "src=/root/1.txt dest=/opt/2.txt backup=yes owner=root group=root mode=644"

The difference between / when copying and without /

ansible hy -m copy -a "src=/etc/yum.repos.d dest=/etc/yum.repos.d"

ansible nginx -m copy -a "src=/etc/yum.repos.d/ dest=/etc/yum.repos.d"

7. The fetch module is similar to the copy module, but has the opposite effect. Used to copy files from a remote machine to the local machine.

Note : The fetch module cannot copy directories from remote to local

##两台agent上创建同名、路径文件
echo 192.168.115.136 hy > test.txt
echo 192.168.115.140 nginx > test.txt
###ansible上操作
group -m fetch -a "src=/etc/yum.repos.d/test.txt dest=/etc/yum.repos.d"

8. user module

The user module is used to manage user accounts and user attributes.

##创建aaa用户,默认为普通用户,创建家目录
ansible hy -m user -a "name=aaa state=present"

###创建系统用户
ansible hy -m user -a'name=bbb state=present system=yes shell="/sbin/nologin"'

##创建ccc用户, 使用uid参数指定uid, 使用password参数传密码
echo 123.com |openssl passwd -stdin
ansible hy -m user -a 'name=ccc state=present uid=6666 password="密码"'

##创建一个普通用户叫ddd,并产生空密码 密钥对
ansible hy -m user -a 'name=ddd state=present generate_ssh_key=yes'

##删除aaa用户,但家目录默认没有删除
ansible hy -m user -a 'name=aaa state=absent'

##删除aaa用户、家目录
ansible hy -m user -a 'name=aaa state=absent remove=yes'

9. group module

The group module is used to manage user groups and user group attributes.

###创建组
ansible hy -m group -a 'name=web gid=2000 state=present'

##删除组(如果有用户的gid为此组,则删除不了)
ansible hy -m group -a 'name=web state=absent'

10. cron module

The cron module is used to manage periodic time tasks

##创建一个cron任务,不指定user的话,默认就是root(因为我这里是用root操作的)。
如果minute,hour,day,month,week不指定的话,默认都为*
ansible hy -m cron -a 'name="test1" user=root job="touch /etc/6666" minute=26'

删除cron任务
ansible hy -m cron -a 'name="test1" state=sbsent'

4. yum_repository module

The yum_repository module is used to configure the yum repository.

### yum_repository模块yum_repository模块用于配置yum仓库。
注意:此模块只帮助配置yum仓库,但如果仓库里没有软件包,安装一样会失败。所以可以手动去挂载光驱到/mnt目录


ansible hy -m yum_repository -a "name=local description=localyum baseurl=file:///mnt/ enabled=yes gpgcheck=no"


##删除/etc/yum.repos.d/local.repo配置文件
ansible hy -m yum_repository -a "name=local state=absent"

5. yum module

The yum module is used to install and uninstall software packages using the yum command. Prerequisite: The yum configuration on the group machine is OK. If you use local sources, you need to mount them.

##安装http
ansible group -m yum -a 'name=httpd state=present'
######使用网络源
##在ansible上安安装网络源
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
##copy到其他主机

Use yum to install httpd, httpd-devel software, state=latest means installing the latest version

ansible group1 -m yum -a 'name=httpd,httpd-devel state=latest'

Use yum to uninstall httpd, httpd-devel software

ansible group1 -m yum -a 'name=httpd,httpd-devel state=absent'

6. Server module

### service模块(重点)service模块用于控制服务的启动,关闭,开机自启动等。
启动vsftpd服务,并设为开机自动启动
master# ansible group -m service -a 'name=vsftpd state=started enabled=on'

关闭vsftpd服务,并设为开机不自动启动
master# ansible group -m service -a 'name=vsftpd state=stoped enabled=false'

We install a mariadb service and set it to start automatically at boot

ansible group -m yum -a 'name=mariadb,mariadb-server state=present'
ansible group -m service -a 'name=mariadb state=started enabled=yes'

7. script module

The script module is used to execute local scripts on remote machines .

在master上准备一个脚本
master# vim /tmp/1.sh
#!/bin/bash
mkdir /tmp/haha
touch /tmp/haha/{1..10}

在group1的远程机器里都执行master上的/tmp/1.sh脚本(此脚本不用给执行权限)
master# ansible group1 -m script -a '/tmp/1.sh'

8. command and shell modules

Both modules are used to execute Linux commands, which is very easy to use for engineers who are familiar with the commands.

The shell module is similar to the command module (the command module cannot execute symbols such as $HOME, >, <, |, etc., but the shell can)

 ansible -m command group1 -a "useradd user2"
ansible -m command group1 -a "id user2"
ansible -m command group1 -a "cat /etc/passwd |wc -l"       --报错
ansible -m shell group1 -a "cat /etc/passwd |wc -l"     --成功
ansible -m command group1 -a "cd $HOME;pwd" --error report
ansible -m shell  group1 -a "cd $HOME;pwd"    --成功

Note: The shell module is not 100% compatible with any command, such as vim or ll aliases. It is not recommended that you memorize which commands are not allowed. You just need to develop the habit of testing any command in the production environment in the test environment first.

9. playbook

Playbook: is a playbook used by Ansible to configure, deploy, and manage controlled nodes. Orchestration for Ansible operations.

The format used is yaml format (saltstack, elk, docker, docker-compose, kubernetes, etc. also use yaml format)

YMAL format

  • End with .yaml or .yml

  • The first line of the file starts with "---", indicating the beginning of the YMAL file (optional)

  • Comments starting with # sign

  • All members of the list start at the same indentation level and start with a "- "(a dash and a space)

  • A dictionary is 键: 值composed of a simple form (the colon must be followed by a space)

  • ==Note: Do not use the tab key when writing this kind of file, use spaces==

## playbook实例

先直接来看一个实例

**第1步: 创建一个存放playbook的目录(路径自定义)**

```powershell
master# mkdir /etc/ansible/playbook
```

**第2步: 准备httpd配置文件,并修改成你想要的配置**

```powershell
master# yum install httpd -y

按需要修改你想要的配置(为了测试可以随意改动标记一下)
master# vim /etc/httpd/conf/httpd.conf
```

**第3步: 写一个playbook文件(后缀为.yml或.yaml)**

```powershell
# vim /etc/ansible/playbook/example.yaml
---
- hosts: group1
  remote_user: root
  tasks:  
  - name: ensure apache is at the latest version	
    yum: name=httpd,httpd-devel state=latest
    
  - name: write the apache config file		
    copy: src=/etc/httpd/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
    
    notify:
    - restart apache
    
  - name: ensure apache is running (and enable it at boot)
    service: name=httpd state=started enabled=yes
    
  handlers:	
    - name: restart apache
      service: name=httpd state=restarted
```

第4步: 执行写好的palybook

- 会显示出执行的过程,并且执行的每一步都有ok,changed,failed等标识
- 执行如果有错误(failed)会回滚,解决问题后,直接再执行这条命令即可,并会把failed改为changed(幂等性)

```powershell
# ansible-playbook /etc/ansible/playbook/example.yaml
```



## Playbook常见语法

**hosts:** 用于指定要执行任务的主机,其可以是一个或多个由冒号分隔主机组.

**remote_user:** 用于指定远程主机上的执行任务的用户.

```powershell
- hosts: group1			
  remote_user: root	
```



**tasks:** 任务列表, 按顺序执行任务. 

- 如果一个host执行task失败, 整个tasks都会回滚, 修正playbook 中的错误, 然后重新执行即可.

```powershell
  tasks:
  - name: ensure apache is at the latest version	
    yum: name=httpd,httpd-devel state=latest
    
  - name: write the apache config file		
    copy: src=/etc/httpd/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
```



**handlers:**  类似task,但需要使用notify通知调用。

- 不管有多少个通知者进行了notify,等到play中的所有task执行完成之后,handlers也只会被执行一次.
- handlers最佳的应用场景是用来重启服务,或者触发系统重启操作.除此以外很少用到了.

```powershell
    notify:				  
    - restart apache
    
  - name: ensure apache is running (and enable it at boot)
    service: name=httpd state=started enabled=yes
    
  handlers:
  - name: restart apache
    service: name=httpd state=restarted
```



**练习:** 修改httpd的端口为8080,再执行playbook测试



**variables:** 变量

- 定义变量可以被多次方便调用

```powershell
master# vim /etc/ansible/playbook/example2.yaml
---
- hosts: group1
  remote_user: root
  vars:
  - user: test1
  tasks:
  - name: create user
    user: name={
   
   {user}} state=present
~                                           
```

```powershell
master# ansible-playbook /etc/ansible/playbook/example2.yaml
```



### 案例: playbook编排vsftpd

写一个playbook实现 

1. 配置yum
2. 安装vsftpd包
3. 修改配置文件(要求拒绝匿名用户登录)
4. 启动服务并实现vsftpd服务开机自动启动

```powershell
---
- hosts: group1                 
  remote_user: root                     
  tasks:                                
  - name: rm yum repository      
    file: path=/etc/yum.repos.d/ state=absent
    
  - name: 同步master上的yum源到group1
    copy: src=/etc/yum.repos.d dest=/etc/
    
  - name: ensure vsftpd is at the latest version        
    yum: name=vsftpd state=latest
    
  - name: write the apache config file          
    copy: src=/etc/vsftpd/vsftpd.conf dest=/etc/vsftpd/vsftpd.conf 
    
    notify:                             
    - restart vsftpd
    
  - name: ensure vsftpd is running (and enable it at boot)
    service: name=vsftpd state=started enabled=yes
    
  handlers:                     
    - name: restart vsftpd              
      service: name=vsftpd state=restarted
```



## **playbook编排多个hosts任务**

~~~powershell
---			# ---代表开始(可选项,不写也可以)
- hosts: 10.1.1.12
  remote_user: root
  tasks:
  - name: 创建/test1/目录
    file: path=/test1/ state=directory
# 这里不能用---分隔,会报语法错误(后面课程玩k8s编排也写YAML文件,是可以用---来分隔段落的)
- hosts: 10.1.1.13
  remote_user: root
  tasks:
  - name: 创建/test2/目录
    file: path=/test2/ state=directory
...			# ...代表结束(可选项,不写也可以)
~~~



### 案例: 编排nfs搭建与客户端挂载

1, 在master上准备nfs配置文件

~~~powershell
# vim /etc/exports
/share  *(ro)
~~~

2, 编写yaml编排文件

~~~powershell
# vim /etc/ansible/playbook/nfs.yml
---
- hosts: 10.1.1.12
  remote_user: root
  tasks:
  - name: 安装nfs服务相关软件包
    yum: name=nfs-utils,rpcbind,setup  state=latest

  - name: 创建共享目录
    file: path=/share/ state=directory

  - name: 同步nfs配置文件
    copy: src=/etc/exports dest=/etc/exports

    notify: restart nfs

  - name: 启动rpcbind服务,并设置为开机自启动
    service: name=rpcbind state=started enabled=on

  - name: 启动nfs服务,并设置为开机自启动
    service: name=nfs state=started enabled=on

  handlers:
  - name: restart nfs
    service: name=nfs state=restarted

- hosts: 10.1.1.13
  remote_user: root
  tasks:
  - name: 安装nfs客户端软件包
    yum: name=nfs-utils state=latest

  - name: 挂载nfs服务器的共享
    shell: mount 10.1.1.12:/share /mnt
~~~

3, 执行playbook

~~~powershell
# ansible-playbook /etc/ansible/playbook/nfs.yaml
~~~

Guess you like

Origin blog.csdn.net/2302_78534730/article/details/132721068