运维自动化之ANSIBLE

运维自动化之ANSIBLE

运维自动化之ANSIBLE

本章内容

  • 运维自动化发展历程及技术应用

  • Ansible命令使用

  • Ansible常用模块详解

  • YAML语法简介

  • Ansible playbook基础

  • Playbook变量、tags、handlers使用

  • Playbook模板 templates

  • Playbook条件判断 when

  • Playbook字典 with_items

  • Ansible Roles

1 自动化运维应用场景

1.1 云计算运维工程师核心职能

在这里插入图片描述

相关工具

  • 代码管理(SCM):GitHub、GitLab、BitBucket、SubVersion

  • 构建工具:maven、Ant、Gradle

  • 自动部署:Capistrano、CodeDeploy

  • 持续集成(CI):Jenkins、Travis

  • 配置管理:Ansible、SaltStack、Chef、Puppet

  • 容器:Docker、Podman、LXC、第三方厂商如AWS

  • 编排:Kubernetes、Core、Apache Mesos

  • 服务注册与发现:Zookeeper、etcd、Consul

  • 脚本语言:python、ruby、shell

  • 日志管理:ELK、Logentries

  • 系统监控:Prometheus、Zabbix、Datadog、Graphite、Ganglia、Nagios

  • 性能监控:AppDynamics、New Relic、Splunk

  • 压力测试:JMeter、Blaze Meter、loader.io

  • 应用服务器:Tomcat、JBoss、IIS

  • Web服务器:Apache、Nginx

  • 数据库:MySQL、Oracle、PostgreSQL等关系型数据库;mongoDB、redis等NoSQL数据库

  • 项目管理(PM):Jira、Asana、Taiga、Trello、Basecamp、Pivotal Tracker

1.2 运维职业发展路线

在这里插入图片描述
运维的未来是什么?

一切皆自动化

“运维的未来是,让研发人员能够借助工具、自动化和流程,并且让他们能够在运维干预极少的情况下 部署和运营服务,从而实现自助服务。每个角色都应该努力使工作实现自动化。”——《运维的未来》

1.3 企业实际应用场景分析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WLl3inug-1592754503994)(G:Tptupian\1.3.PNG)]

1.3.1 Dev开发环境

使用者:程序员

功能:程序员个人的办公电脑或项目的开发测试环境,部署开发软件,测试个人或项目整体的BUG的 环境

管理者:程序员

1.3.2 测试环境

使用者:QA测试工程师

功能:测试经过Dev环境测试通过的软件的功能和性能,判断是否达到项目的预期目标,生成测试报 告

管理者:运维

说明:测试环境往往有多套,测试环境满足测试功能即可,不宜过多

1、测试人员希望测试环境有多套,公司的产品多产品线并发,即多个版本,意味着多个版本同步测试

2、通常测试环境有多少套和产品线数量保持一样

1.3.3 预发布环境

在这里插入图片描述
使用者:运维

功能:使用和生产环境一样的数据库,缓存服务等配置,测试是否正常

1.3.4 发布环境

包括代码发布机,有些公司为堡垒机(安全屏障)

使用者:运维

功能:发布代码至生产环境

管理者:运维(有经验)

发布机:往往需要有2台(主备)

1.3.5 生产环境

使用者:运维,少数情况开放权限给核心开发人员,极少数公司将权限完全开放给开发人员并其维护

功能:对用户提供公司产品的服务

管理者:只能是运维 生产环境服务器数量:一般比较多,且应用非常重要。往往需要自动工具协助部署配置应用

1.3.6 灰度环境

属于生产环境的一部分

使用者:运维

功能:在全量发布代码前将代码的功能面向少量精准用户发布的环境,可基于主机或用户执行灰度发布 案例:共100台生产服务器,先发布其中的10台服务器,这10台服务器就是灰度服务器

管理者:运维

灰度环境:往往该版本功能变更较大,为保险起见特意先让一部分用户优化体验该功能,待这部分用 户使用没有重大问题的时候,再全量发布至所有服务器

1.4 程序发布

程序发布要求: 不能导致系统故障或造成系统完全不可用 不能影响用户体验

预发布验证: 新版本的代码先发布到服务器(跟线上环境配置完全相同,只是未接入到调度器)

灰度发布:

基于主机,用户,业务

发布路径:

软链接技术:软件的升级和回滚其实就是软链接指向的路径改变

/webapp/tuangou

/webapp/tuangou-1.1

/webapp/tuangou-1.2

发布过程:

  1. 在调度器上下线一批主机(标记为maintenance 状态)
  2. 关闭服务
  3. 部署新版本的应用程序
  4. 启动服务
  5. 在调度器上启用这一批服务器

自动化灰度发布:

  • 脚本
  • 发布平台
1.5 自动化运维应用场景
  • 文件传输
  • 应用部署
  • 配置管理
  • 任务流编排
1.6 常用自动化运维工具
  • Ansible:python,Agentless(无代理),中小型应用环境

  • Saltstack:python,一般需部署agent,执行效率更高

  • Puppet:ruby, 功能强大,配置复杂,重型,适合大型环境

  • Fabric:python,agentless Chef:ruby,国内应用少 Cfengine

  • func

    https://github.com/ansible/ansible https://github.com/Saltstack/salt
    在这里插入图片描述
    在这里插入图片描述
    同类自动化工具GitHub关注程度(2016-07-10)

自动化运维工 具 Watch(关 注) Star(点 赞) Fork(复 制) Contributors(贡献 者)
Ansible 1387 17716 5356 1428
Saltstack 530 6678 3002 1520
Puppet 463 4044 1678 425
Chef 383 4333 1806 464
Fabric 379 7334 1235 116

2 Ansible 介绍和架构

公司计划在年底做一次大型市场促销活动,全面冲刺下交易额,为明年的上市做准备。公司要求各业务 组对年底大促做准备,运维部要求所有业务容量进行三倍的扩容,并搭建出多套环境可以共开发和测试 人员做测试,运维老大为了在年底有所表现,要求运维部门同学尽快实现,当你接到这个任务时,有没 有更快的解决方案?

2.1 Ansible发展史

作者:Michael DeHaan( Cobbler 与 Func 作者)

ansible 的名称来自科幻小说《安德的游戏》中跨越时空的即时通信工具,使用它可以在相距数光年的 距离,远程实时控制前线的舰队战斗。

2012-03-09,发布0.0.1版,2015-10-17,Red Hat宣布1.5亿美元收购

官网:https://www.ansible.com/

官方文档:https://docs.ansible.com/

2.2 Ansible 特性

  • 模块化:调用特定的模块完成特定任务,支持自定义模块,可使用任何编程语言写模块
  • Paramiko(python对ssh的实现),PyYAML,Jinja2(模板语言)三个关键模块 基于Python语言实现
  • 部署简单,基于python和SSH(默认已安装),agentless,无需代理不依赖PKI(无需ssl)
  • 安全,基于OpenSSH
  • 幂等性:一个任务执行1遍和执行n遍效果一样,不因重复执行带来意外情况
  • 支持playbook编排任务,YAML格式,编排任务,支持丰富的数据结构
  • 较强大的多层解决方案 role

2.3 Ansible 架构

2.3.1 Ansible 组成

组合INVENTORY、API、MODULES、PLUGINS的绿框,为ansible命令工具,其为核心执行工具

在这里插入图片描述

2.3.2 Ansible 命令执行来源
  • USER 普通用户,即SYSTEM ADMINISTRATOR
  • PLAYBOOKS:任务剧本(任务集),编排定义Ansible任务集的配置文件,由Ansible顺序依次执 行,通常是JSON格式的YML文件
  • CMDB(配置管理数据库) API 调用 PUBLIC/PRIVATE CLOUD API调用
  • USER-> Ansible Playbook -> Ansibile
2.3.3 注意事项
  • 执行ansible的主机一般称为主控端,中控,master或堡垒机
  • 主控端Python版本需要2.6或以上
  • 被控端Python版本小于2.4,需要安装python-simplejson
  • 被控端如开启SELinux需要安装libselinux-python
  • windows 不能做为主控端

Ansible无代理,通过ssh协议就可以管理,不是一个独立服务,没有以service结尾的文件,abslble是管理端,需要的时候连接,不需要的时候就不连接。ansible不是一个时时刻刻都需要在运行的软件,是临时性运行的,不需要设置为开机启动。

在这里插入图片描述

3 Ansible 安装和入门

3.1 Ansible安装

ansible的安装方法有多种

3.1.1 EPEL源的rpm包安装:
[root@ansible ~]#yum install ansible
3.1.2 编译安装
yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto
tar xf ansible-1.5.4.tar.gz
cd ansible-1.5.4
python setup.py build
python setup.py install
mkdir /etc/ansible
cp -r examples/* /etc/ansible
3.1.3 Git方式
git clone git://github.com/ansible/ansible.git --recursive
cd ./ansible
source ./hacking/env-setup
3.1.4 pip 安装

pip 是安装Python包的管理器,类似 yum

yum install python-pip python-devel
yum install gcc glibc-devel zibl-devel rpm-bulid openssl-devel
pip install  --upgrade pip
pip install ansible --upgrade
3.1.5 确认安装
[root@ansible ~]#ansible --version
ansible 2.9.5
 config file = /etc/ansible/ansible.cfg
 configured module search path = ['/root/.ansible/plugins/modules',
'/usr/share/ansible/plugins/modules']
 ansible python module location = /usr/lib/python3.6/site-packages/ansible
 executable location = /usr/bin/ansible
 python version = 3.6.8 (default, Nov 21 2019, 19:31:34) [GCC 8.3.1 20190507
(Red Hat 8.3.1-4)]

3.2 Ansible 相关文件

3.2.1 配置文件
  • /etc/ansible/ansible.cfg 主配置文件,配置ansible工作特性
  • /etc/ansible/hosts 主机清单
  • /etc/ansible/roles/ 存放角色的目录
3.2.2 ansible主配置文件

Ansible 的配置文件 /etc/ansible/ansible.cfg ,其中大部分的配置内容无需进行修改 ,以下建议修改

建议开启日志文件,会记录ansible对被管理者执行了哪些操作就,会记录在/var/log/ansible.log文件中,

不开启则没有这个文件。

host_key_checking = False开启,基于key验证,即通过ssh连接被管理端不用敲yes。

或者将ssh配置文件/etc/ssh/ssh_config中 # StrictHostKeyChecking ask 选项改为StrictHostKeyChecking no

[defaults]
#inventory     = /etc/ansible/hosts        # 主机列表配置文件
#library = /usr/share/my_modules/          # 库文件存放目录
#remote_tmp = $HOME/.ansible/tmp           # 临时py命令文件存放在远程主机目录
#local_tmp     = $HOME/.ansible/tmp        # 本机的临时命令执行目录
#forks         = 5                         # 默认并发数
#sudo_user     = root                      # 默认sudo 用户
#ask_sudo_pass = True                      # 每次执行ansible命令是否询问ssh密码
#ask_pass     = True  
#remote_port   = 22
#host_key_checking = False                 # 检查对应服务器的host_key,建议取消注释
#log_path=/var/log/ansible.log             # 日志文件,建议启用
#module_name = command                     # 默认模块,可以修改为shell模块
3.2.3 inventory 主机清单

ansible的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名

默认的inventory file为 /etc/ansible/hosts inventory

file可以有多个,且也可以通过Dynamic Inventory来动态生成

主机清单文件格式

inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中

此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明

如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机

范例:

ntp.magedu.com
[webservers]
www1.magedu.com:2222
www2.magedu.com
[dbservers]
db1.magedu.com
db2.magedu.com
db3.magedu.com
[websrvs]
www[1:100].example.com
[dbsrvs]
db-[a:f].example.com
[appsrvs]
10.0.0.[1:100]

实验:连接被管理端

[root@ansible ~]#vim /etc/ansible/ansible.cfg 
log_path = /var/log/ansible.log
host_key_checking = False

[root@ansible ~]#vim /etc/ansible/hosts 
[websrvs]
10.0.0.8
10.0.0.7

[appsrvs]
10.0.0.6

[dbsrvs]
10.0.0.8
10.0.0.18

[root@ansible ~]#ansible all --list
  hosts (5):
    10.0.0.8
    10.0.0.7
    10.0.0.6
    10.0.0.18
[root@ansible ~]#ansible websrvs --list
  hosts (2):
    10.0.0.8
    10.0.0.7
[root@ansible ~]#ansible appsrvs --list
  hosts (2):
    10.0.0.6   
[root@ansible ~]#ansible dbsrvs --list
  hosts (2):
    10.0.0.8
    10.0.0.18


#没有配置基于key验证,则不可达
[root@ansible ~]#ansible all -m ping 
10.0.0.18 | UNREACHABLE! => {
   
   
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '10.0.0.18' (ECDSA) to the list of known hosts.\r\[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}
10.0.0.8 | UNREACHABLE! => {
   
   
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '10.0.0.8' (ECDSA) to the list of known hosts.\r\[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}
10.0.0.6 | UNREACHABLE! => {
   
   
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '10.0.0.6' (RSA) to the list of known hosts.\r\[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}
10.0.0.7 | UNREACHABLE! => {
   
   
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '10.0.0.7' (ECDSA) to the list of known hosts.\r\[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}

#因为修改了配置文件host_key_checking = False选项,则把管理的主机的公钥下载到本地
[root@ansible ~]#ls .ssh
known_hosts
[root@ansible ~]#cd .ssh
[root@ansible .ssh]#cat known_hosts 
10.0.0.8 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIgQHXFnlcUSqBKPvpnQH4BCgFwFoF1XUfH/jRLgj+LjAfUCxO5KH0NGN4M/C4XVWCcOBEVbDmHBTQsxGsoB0Cc=
10.0.0.18 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIgQHXFnlcUSqBKPvpnQH4BCgFwFoF1XUfH/jRLgj+LjAfUCxO5KH0NGN4M/C4XVWCcOBEVbDmHBTQsxGsoB0Cc=
10.0.0.6 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA13SMVX1GDoav1P7eXAQUbojEkWEasxvocWRsuZfjy0hEwzFMsw/x901QuMe4LtfJxWXYN4U/1jyfO158kIKH5JonwD52F8IeT9EQdaYucTO+p2veAwmztXpz2QWwLBcYvLvqX5jgKxYZ2gnnjhiW46kENlKL1+YReYqdhENfJkH9j6Ep1iZnAUAsjm9Q7K9qTX524JDOWfOei5MkjfM1l2T0nDI6rLCSOW/z9doi3Bob8t+100N4jcdu6Fe6+8dXd1T1WMaMh0ziztONujHOREUs6KQ2TtOUYgaYXlh/WE1Ur+Pb88l0Q1xD5puoNaiCFY9j4x/f2HwPRbr7JkCDuw==
10.0.0.7 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDjiC5jrh6lR+fdBKZlGt84/3vUonsPLZ3Dsx9wndpSXcKHNL6I4QNevqlS1tf2Rpdns4MlpoBIkJcX/5I9pGUE=

#配置基于key验证
[root@ansible ~]#vim ssh_push_key.sh
#!/bin/bash
IPLIST="
10.0.0.8
10.0.0.18
10.0.0.7
10.0.0.6"
rpm -q sshpass &> /dev/null || yum -y install sshpass  
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa  -P ''
export SSHPASS=96110933
for IP in $IPLIST;do
	   sshpass -e ssh-copy-id -o StrictHostKeyChecking=no $IP
   done
root@ansible ~]#bash ssh_push_key.sh

[root@ansible ~]#ansible all -m ping
10.0.0.7 | SUCCESS => {
   
   
    "ansible_facts": {
   
   
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.18 | SUCCESS => {
   
   
    "ansible_facts": {
   
   
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.6 | SUCCESS => {
   
   
    "ansible_facts": {
   
   
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.8 | SUCCESS => {
   
   
    "ansible_facts": {
   
   
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

#逻辑
[root@ansible ~]#ansible "websrvs:appsrvs" --list
  hosts (3):
    10.0.0.8
    10.0.0.7
    10.0.0.6
[root@ansible ~]#ansible "websrvs" --list
  hosts (2):
    10.0.0.8
    10.0.0.7
[root@ansible ~]#ansible "appsrvs" --list
  hosts (1):
    10.0.0.6
[root@ansible ~]#ansible "websrvs:&appsrvs" --list
[WARNING]: No hosts matched, nothing to do
  hosts (0):
[root@ansible ~]#ansible "websrvs:&dbsrvs" --list
  hosts (1):
    10.0.0.8
[root@ansible ~]#ansible "dbsrvs" --list
  hosts (2):
    10.0.0.8
    10.0.0.18

#取反需要用单引号,用双引号会出错,会把!当成命令执行,表示前一个命令执行的历史
[root@ansible ~]#ansible "websrvs:!dbsrvs" --list
-bash: !dbsrvs: event not found
[root@ansible ~]#ansible 'websrvs:&dbsrvs' --list
  hosts (1):
    10.0.0.8



#把所有ansible管理的主机全部关闭,但有些没有关闭,
#原因:此处ansible管理了自己,先把自己关闭了,有些主机没来得及关闭
[root@ansible ~]#ansible all -a reboot
#取反应用
#上述解决办法,先关闭别人再关闭自己
[root@ansible ~]#ansible 'all:!10.0.0.18' -a reboot; reboot

扩展知识点:Ubuntu修改密码

[root@ubuntu1804 ~]#echo root:ubuntu|chpasswd
[root@ubuntu1804 ~]#su - rain
[rain@ubuntu1804 ~]$su -
Password: 
[root@ubuntu1804 ~]#echo -e '96110933\n96110933' |passwd
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully

3.3 Ansible相关工具

  • /usr/bin/ansible 主程序,临时命令执行工具
  • /usr/bin/ansible-doc 查看配置文档,模块功能查看工具,相当于man
  • /usr/bin/ansible-playbook 定制自动化任务,编排剧本工具,相当于脚本
  • /usr/bin/ansible-pull 远程执行命令的工具
  • /usr/bin/ansible-vault 文件加密工具
  • /usr/bin/ansible-console 基于Console界面与用户交互的执行工具
  • /usr/bin/ansible-galaxy 下载/上传优秀代码或Roles模块的官网平台

利用ansible实现管理的主要方式:

  • Ad-Hoc 即利用ansible命令,主要用于临时命令使用场景
  • Ansible-playbook 主要用于长期规划好的,大型项目的场景,需要有前期的规划过程
3.3.1 ansible-doc

此工具用来显示模块帮助

格式

ansible-doc [options] [module...]
-l, --list       #列出可用模块
-s, --snippet    #显示指定模块的playbook片段

范例:

#列出所有模块
ansible-doc -l  
#查看指定模块帮助用法
ansible-doc ping  
#查看指定模块帮助用法
ansible-doc -s  ping

范例:

[root@ansible ~]#date
Wed Jun 17 16:08:09 CST 2020
[root@ansible ~]#ansible --version
ansible 2.9.9
 config file = /etc/ansible/ansible.cfg
 configured module search path = ['/root/.ansible/plugins/modules',
'/usr/share/ansible/plugins/modules']
 ansible python module location = /usr/lib/python3.6/site-packages/ansible
 executable location = /usr/bin/ansible
 python version = 3.6.8 (default, Apr 16 2020, 01:36:27) [GCC 8.3.1 20191121
(Red Hat 8.3.1-5)]
[root@ansible ~]#ansible-doc -l|wc -l
3387

范例:ping模块

#ping模块用来连接目标主机,校验对方是否支持本方ssh连接,是否能够通过ansible远程进行管理

[root@ansible ~]#ansible-doc -l| grep '^ping'
ping                                                          Try to connect to host, verify a usable python and ...
pingdom                                                       Pause/unpause Pingdom alerts                       

#ping模块用法,其本身就是一个python程序,属于核心模块,不属于第三方扩展模块
[root@ansible ~]#ansible-doc ping
> PING    (/usr/lib/python3.6/site-packages/ansible/modules/system/ping.py)

        A trivial test module, this module always returns `pong' on successful contact. It
        does not make sense in playbooks, but it is useful from `/usr/bin/ansible' to verify
        the ability to login and that a usable Python is configured. This is NOT ICMP ping,
        this is just a trivial test module that requires Python on the remote-node. For
        Windows targets, use the [win_ping] module instead. For Network targets, use the
        [net_ping] module instead.

  * This module is maintained by The Ansible Core Team
OPTIONS (= is mandatory):

- data
        Data to return for the `ping' return value.
        If this parameter is set to `crash', the module will cause an exception.
        [Default: pong]
        type: str


SEE ALSO:
      * Module net_ping
           The official documentation on the net_ping module.
           https://docs.ansible.com/ansible/2.9/modules/net_ping_module.html
      * Module win_ping
           The official documentation on the win_ping module.
           https://docs.ansible.com/ansible/2.9/modules/win_ping_module.html


AUTHOR: Ansible Core Team, Michael DeHaan
        METADATA:
          status:
          - stableinterface
          supported_by: core

EXAMPLES:

# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping

# Example from an Ansible Playbook
- ping:

# Induce an exception to see what happens
- ping:
    data: crash


RETURN VALUES:

ping:
    description: value provided with the data parameter
    returned: success
    type: str
    sample: pong

(END)  

#查看ping最重要的用法

[root@ansible ~]#ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the
                               module will cause an exception.

3.3.2 ansible

此工具通过ssh协议,实现对远程主机的配置管理、应用部署、任务执行等功能

建议:使用此工具前,先配置ansible主控端能基于密钥认证的方式联系各个被管理节点

范例:利用sshpass批量实现基于key验证脚本1

[root@centos8 ~]#vim /etc/ssh/ssh_config
#修改下面一行
StrictHostKeyChecking no
[root@centos8 ~]#cat hosts.list
10.0.0.18
10.0.0.28
[root@centos8 ~]#vim push_ssh_key.sh
#!/bin/bash
rpm -q sshpass &> /dev/null || yum -y install sshpass  
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa  -P ''
export SSHPASS=magedu
while read IP;do
   sshpass -e ssh-copy-id  -o StrictHostKeyChecking=no $IP
done < hosts.list

范例: 实现基于key验证的脚本2

[root@centos8 ~]#vim push_ssh_key.sh
#!/bin/bash
IPLIST="
10.0.0.8
10.0.0.18
10.0.0.7
10.0.0.6
10.0.0.200"
rpm -q sshpass &> /dev/null || yum -y install sshpass  
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa  -P ''
export SSHPASS=centos
for IP in $IPLIST;do
   sshpass -e ssh-copy-id -o StrictHostKeyChecking=no $IP
done

格式:

ansible <host-pattern> [-m module_name] [-a args]

选项说明:

--version               #显示版本
-m module               #指定模块,默认为command
-v                      #详细过程 –vv -vvv更详细
--list-hosts            #显示主机列表,可简写 --list
-k, --ask-pass          #提示输入ssh连接密码,默认Key验证
-C, --check             #检查,并不执行
-T, --timeout=TIMEOUT   #执行命令的超时时间,默认10s
-u, --user=REMOTE_USER  #执行远程执行的用户
-b, --become            #代替旧版的sudo 切换
--become-user=USERNAME  #指定sudo的runas用户,默认为root
-K, --ask-become-pass   #提示输入sudo时的口令

范例:

[root@ansible ~]#ansible all -v -m shell -a 'ls'
Using /etc/ansible/ansible.cfg as config file
10.0.0.7 | CHANGED | rc=0 >>
anaconda-ks.cfg
10.0.0.6 | CHANGED | rc=0 >>
anaconda-ks.cfg
install.log
install.log.syslog
10.0.0.8 | CHANGED | rc=0 >>
anaconda-ks.cfg
hellodb_innodb.sql
ifcfg-eth0
mha4mysql-node-0.56-0.el6.noarch.rpm
testlog.sql
10.0.0.18 | CHANGED | rc=0 >>
anaconda-ks.cfg
hello.yml
ifcfg-eth0
ssh_push_key.sh

#可以重定向到一个文件中详细观察
[root@ansible ~]#ansible all -vv -m shell -a 'ls' > ansible.log
[root@ansible ~]#vim ansible.log 

ansible 2.9.9
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Nov 21 2019, 19:31:34) [GCC 8.3.1 20190507 (Red Hat 8.3.1-4)]
Using /etc/ansible/ansible.cfg as config file
META: ran handlers
10.0.0.7 | CHANGED | rc=0 >>
anaconda-ks.cfg
10.0.0.6 | CHANGED | rc=0 >>
anaconda-ks.cfg
install.log
install.log.syslog
10.0.0.8 | CHANGED | rc=0 >>
anaconda-ks.cfg
hellodb_innodb.sql
ifcfg-eth0
mha4mysql-node-0.56-0.el6.noarch.rpm
testlog.sql
10.0.0.18 | CHANGED | rc=0 >>
anaconda-ks.cfg
ansible.log
hello.yml
ifcfg-eth0
ssh_push_key.sh
META: ran handlers
META: ran handlers

ansible的Host-pattern

用于匹配被控制的主机的列表

All :表示所有Inventory中的所有主机

范例

ansible all –m ping

*:通配符

ansible "*” -m ping
ansible 192.168.1.* -m ping
ansible "srvs” -m ping

或关系

 ansible "websrvs:appsrvs" -m ping 
 ansible "192.168.1.10:192.168.1.20" -m ping 

逻辑与

#在websrvs组并且在dbsrvs组中的主机
ansible "websrvs:&dbsrvs" –m ping

逻辑非

#在websrvs组,但不在dbsrvs组中的主机
#注意:此处为单引号
ansible 'websrvs:!dbsrvs' –m ping

综合逻辑

ansible 'websrvs:dbsrvs:&appsrvs:!ftpsrvs' –m ping

正则表达式

ansible "websrvs:dbsrvs" –m ping
ansible "~(web|db).*\.magedu\.com" –m ping

范例:

[root@kube-master1 ~]#ansible 'kube*:etcd:!10.0.0.101' -a reboot

ansible命令执行过程

  1. 加载自己的配置文件 默认/etc/ansible/ansible.cfg
  2. 加载自己对应的模块文件,如:command
  3. 通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户 $HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件
  4. 给文件+x执行
  5. 执行并返回结果
  6. 删除临时py文件,退出

范例:

[root@ansible ~]#ansible all -m shell -a 'sleep 10'
10.0.0.7 | CHANGED | rc=0 >>

10.0.0.6 | CHANGED | rc=0 >>

10.0.0.8 | CHANGED | rc=0 >>

10.0.0.18 | CHANGED | rc=0 >>

#10秒结束,临时文件删除,py程序能不能执行和被管理端的版本有关
[root@centos7 ~]#tree .ansible/tmp/
.ansible/tmp/
└── ansible-tmp-1592491558.6252227-3665-11109623338293
    └── AnsiballZ_command.py

1 directory, 1 file
[root@centos7 ~]#tree .ansible/tmp/
.ansible/tmp/

0 directories, 0 files

ansible 的执行状态:

  • 绿色:执行成功并且不需要做改变的操作
  • 黄色:执行成功并且对目标主机做变更
  • 红色:执行失败
[root@centos8 ~]#grep -A 14 '\[colors\]' /etc/ansible/ansible.cfg
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan

ansible使用范例

#以wang用户执行ping存活检测
ansible all -m ping -u wang  -k
#以wang sudo至root执行ping存活检测
ansible all -m ping -u wang -k -b
#以wang sudo至mage用户执行ping存活检测
ansible all -m ping -u wang -k -b --become-user=mage
#以wang sudo至root用户执行ls
ansible all -m command  -u wang -a 'ls /root' -b --become-user=root -k -K
3.3.3 ansible-playbook

此工具用于执行编写好的 playbook 任务

范例:

[root@ansible ~]vim hello.yml
---
#hello world yml file
- hosts: websrvs
 remote_user: root  
 tasks:
    - name: hello world
     command: /usr/bin/wall hello world
    
[root@ansible ~]#ansible-playbook hello.yml 
PLAY [websrvs] *******************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************
ok: [10.0.0.7]
ok: [10.0.0.8]

TASK [hello world] ***************************************************************************************************
changed: [10.0.0.7]
changed: [10.0.0.8]

PLAY RECAP ***********************************************************************************************************
10.0.0.7                   : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.0.0.8                   : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


3.3.4 ansible-vault

此工具可以用于加密解密yml文件

格式:

ansible-vault [create|decrypt|edit|encrypt|rekey|view]

范例

ansible-vault encrypt hello.yml     #加密
ansible-vault decrypt hello.yml     #解密
ansible-vault view hello.yml        #查看
ansible-vault edit hello.yml        #编辑加密文件
ansible-vault rekey hello.yml       #修改口令
ansible-vault create new.yml        #创建新文件

范例:

#对hello.yml加密
[root@ansible ~]#ansible-vault encrypt hello.yml 
New Vault password: 
Confirm New Vault password: 
Encryption successful
[root@ansible ~]#ll hello.yml 
-rw------- 1 root root 873 Jun 18 21:59 hello.yml
[root@ansible ~]#cat hello.yml 
$ANSIBLE_VAULT;1.1;AES256
31306334636536363230666339636166353732343531386537613166613434323963316133383234
3136656662363162663863643965363832386635376331320a376332346361356338623165333833
63616361356633666538303563353063356466343761636236313034326365366530633530653236
6466346561653737310a643636313864313361366561333430323865366661303435333666376561
65363233323862613631383830333130396235323438363236623631346330346165323032663134
30636234393361313665626631316263393763643166333136636162343266653961643330316234
65343136396664646238666162653032643130303866323739303562376238616366643839643563
38346532396663346632633434633832363537656531323730613864613564623033366434646235
35623966386536373433663163616238313931313536306634366364366536626231643266373363
61383564306164316263313565313533663163316130346666613436643563303835346531643564
323436396338383966633864336364303032

#加密过后不能执行
[root@ansible ~]#ansible-playbook hello.yml 
ERROR! Attempting to decrypt but no vault secrets found

#解密
[root@ansible ~]#ansible-vault decrypt hello.yml 
Vault password: 
Decryption successful
[root@ansible ~]#cat hello.yml 
#hello world yml file
- hosts: websrvs
  remote_user: root  
  tasks:
    - name: hello world
      command: /usr/bin/wall hello world
[root@ansible ~]#ansible-playbook hello.yml 

PLAY [websrvs] *******************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************
ok: [10.0.0.7]
ok: [10.0.0.8]

TASK [hello world] ***************************************************************************************************
changed: [10.0.0.7]
changed: [10.0.0.8]

PLAY RECAP ***********************************************************************************************************
10.0.0.7                   : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.0.0.8                   : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


3.3.5 ansible-console

此工具可交互执行命令,支持tab,ansible 2.0+新增

提示符格式:

执行用户@当前操作的主机组 (当前组的主机数量)[f:并发数]$

常用子命令:

  • 设置并发数: forks n 例如: forks 10
  • 切换组: cd 主机组 例如: cd web
  • 列出当前组主机列表: list
  • 列出所有的内置命令: ?或help

范例

[root@ansible ~]#ansible-console
Welcome to the ansible console.
Type help or ? to list commands.
root@all (3)[f:5]$ list
10.0.0.8
10.0.0.7
10.0.0.6
root@all (3)[f:5]$ cd websrvs
root@websrvs (2)[f:5]$ list
10.0.0.7
10.0.0.8
root@websrvs (2)[f:5]$ forks 10
root@websrvs (2)[f:10]$ cd appsrvs
root@appsrvs (2)[f:5]$ yum name=httpd state=present
root@appsrvs (2)[f:5]$ service name=httpd state=started
3.3.6 ansible-galaxy

此工具会连接 https://galaxy.ansible.com 下载相应的roles

范例

#列出所有已安装的galaxy
ansible-galaxy list
#安装galaxy
ansible-galaxy install geerlingguy.mysql
ansible-galaxy install geerlingguy.redis
#删除galaxy
ansible-galaxy remove geerlingguy.redis

在这里插入图片描述
在这里插入图片描述

3.4 Ansible常用模块

2015年底270多个模块,2016年达到540个,2018年01月12日有1378个模块,2018年07月15日1852 个模块,2019年05月25日(ansible 2.7.10)时2080个模块,2020年03月02日有3387个模块 虽然模块众多,但最常用的模块也就2,30个而已,针对特定业务只用10几个模块

常用模块帮助文档参考:

https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

默认模块配置

#默认command模块,可进行修改
[root@ansible ~]#vim /etc/ansible/ansible.cfg
# default module name for /usr/bin/ansible
#module_name = command

3.4.1 Command 模块

功能:在远程主机执行命令,此为默认模块,可忽略-m选项

注意:此命令不支持 $VARNAME < > | ; & 等,用shell模块实现

模块说明:可直接调用Linux命令 ,默认模块,可省略不写

[root@ansible ~]#ansible-doc -s command
- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid quoting values
                               that would otherwise be interpreted incorrectly (for
                               example "user name"). Only the string or the list form
                               can be provided, not both.  One or the other must be
                               provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be
                               run.
      free_form:             # The command module takes a free form command to run. There is no actual parameter
                               named 'free form'.
      removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # If set to `yes', append a newline to stdin data.
      strip_empty_ends:      # Strip empty lines from the end of stdout/stderr in result.
      warn:                  # Enable or disable task warnings.

范例:

#查看command模块说明,,可直接调用Linux命令 ,默认模块,可省略不写
[root@ansible ~]#ansible-doc -s command
- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid quoting values
                               that would otherwise be interpreted incorrectly (for
                               example "user name"). Only the string or the list form
                               can be provided, not both.  One or the other must be
                               provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be
                               run.
      free_form:             # The command module takes a free form command to run. There is no actual parameter
                               named 'free form'.
      removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # If set to `yes', append a newline to stdin data.
      strip_empty_ends:      # Strip empty lines from the end of stdout/stderr in result.
      warn:                  # Enable or disable task warnings.


[root@ansible ~]#ansible websrvs -m command -a 'chdir=/etc cat centos-release'
10.0.0.7 | CHANGED | rc=0 >>
CentOS Linux release 7.7.1908 (Core)
10.0.0.8 | CHANGED | rc=0 >>
CentOS Linux release 8.1.1911 (Core)
[root@ansible ~]#ansible websrvs -m command -a 'chdir=/etc creates=/data/f1.txt
cat centos-release'
10.0.0.7 | CHANGED | rc=0 >>
CentOS Linux release 7.7.1908 (Core)
10.0.0.8 | SUCCESS | rc=0 >>
skipped, since /data/f1.txt exists
[root@ansible ~]#ansible websrvs -m command -a 'chdir=/etc removes=/data/f1.txt
cat centos-release'
10.0.0.7 | SUCCESS | rc=0 >>
skipped, since /data/f1.txt does not exist
10.0.0.8 | CHANGED | rc=0 >>
CentOS Linux release 8.1.1911 (Core)



ansible websrvs -m command -a ‘service vsftpd start’
ansible websrvs -m command -a ‘echo magedu |passwd --stdin wang’  
ansible websrvs -m command -a 'rm -rf /data/'
ansible websrvs -m command -a 'echo hello > /data/hello.log'
ansible websrvs -m command -a "echo $HOSTNAME"


[root@ansible ~]#ansible all -m command -a 'hostname'
10.0.0.6 | CHANGED | rc=0 >>
centos6min.rain.org
10.0.0.7 | CHANGED | rc=0 >>
centos7.8.rain.org
10.0.0.8 | CHANGED | rc=0 >>
centos8.1-min.rain.org
10.0.0.18 | CHANGED | rc=0 >>
ansible
[root@ansible ~]#ansible all -a 'hostname'
10.0.0.7 | CHANGED | rc=0 >>
centos7.8.rain.org
10.0.0.6 | CHANGED | rc=0 >>
centos6min.rain.org
10.0.0.8 | CHANGED | rc=0 >>
centos8.1-min.rain.org
10.0.0.18 | CHANGED | rc=0 >>
ansible

#进入/data创建文件,warning是提示你用file模块,如果不利用chdir参数进入目录,默认创建在/root下

#chdir适合编译安装,进入指定目录

[root@ansible ~]#ansible all -a 'chdir=/data touch a.txt'
[WARNING]: Consider using the file module with state=touch rather than running 'touch'.  If you need to use command
because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in
ansible.cfg to get rid of this message.
10.0.0.7 | CHANGED | rc=0 >>

10.0.0.8 | CHANGED | rc=0 >>

10.0.0.6 | CHANGED | rc=0 >>

10.0.0.18 | CHANGED | rc=0 >>

[root@ansible ~]#ansible all -a 'ls  a.txt'
10.0.0.6 | FAILED | rc=2 >>
ls: cannot access a.txt: No such file or directorynon-zero return code
10.0.0.7 | FAILED | rc=2 >>
ls: cannot access a.txt: No such file or directorynon-zero return code
10.0.0.8 | FAILED | rc=2 >>
ls: cannot access 'a.txt': No such file or directorynon-zero return code
10.0.0.18 | FAILED | rc=2 >>
ls: cannot access 'a.txt': No such file or directorynon-zero return code

3.4.2 Shell模块

功能:和command相似,用shell执行命令

模块说明

[root@ansible ~]#ansible-doc -s shell
- name: Execute shell commands on targets
  shell:
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run followed by optional arguments.
      creates:               # A filename, when it already exists, this step will *not* be run.
      executable:            # Change the shell used to execute the command. This expects an absolute path to the
                               executable.
      free_form:             # The shell module takes a free form command to run, as a string. There is no actual
                               parameter named 'free form'. See the examples on how to
                               use this module.
      removes:               # A filename, when it does not exist, this step will *not* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # Whether to append a newline to stdin data.
      warn:                  # Whether to enable task warnings.


范例:

[root@ansible ~]#ansible websrvs -m shell -a "echo $HOSTNAME"
10.0.0.7 | CHANGED | rc=0 >>
ansible
10.0.0.8 | CHANGED | rc=0 >>
ansible
[root@ansible ~]#ansible websrvs -m shell -a 'echo $HOSTNAME'
10.0.0.7 | CHANGED | rc=0 >>
centos7.wangxiaochun.com
10.0.0.8 | CHANGED | rc=0 >>
centos8.localdomain


[root@ansible ~]#ansible websrvs -m shell -a 'echo centos | passwd --stdin wang'
10.0.0.7 | CHANGED | rc=0 >>
Changing password for user wang.
passwd: all authentication tokens updated successfully.
10.0.0.8 | CHANGED | rc=0 >>
Changing password for user wang.
passwd: all authentication tokens updated successfully.
[root@ansible ~]#ansible websrvs -m shell -a 'ls -l /etc/shadow'
10.0.0.7 | CHANGED | rc=0 >>
---------- 1 root root 889 Mar  2 14:34 /etc/shadow
10.0.0.8 | CHANGED | rc=0 >>
---------- 1 root root 944 Mar  2 14:34 /etc/shadow
[root@ansible ~]#ansible websrvs -m shell -a 'echo hello > /data/hello.log'
10.0.0.7 | CHANGED | rc=0 >>
10.0.0.8 | CHANGED | rc=0 >>


[root@ansible ~]#ansible websrvs -m shell -a 'cat /data/hello.log'
10.0.0.7 | CHANGED | rc=0 >>
hello
10.0.0.8 | CHANGED | rc=0 >>
hello

注意:调用bash执行命令 类似 cat /tmp/test.md | awk -F‘|’ ‘{print $1,$2}’ &> /tmp/example.txt 这些 复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器

范例:将shell模块代替command,设为模块

[root@ansible ~]#vim /etc/ansible/ansible.cfg
#修改下面一行
module_name = shell
3.4.3 Script模块

功能:在远程主机上运行ansible服务器上的脚本(无需执行权限)

模块说明

#script模块说明
[root@ansible ~]#ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
  script:
      chdir:                 # Change into this directory on the remote node before running the script.
      cmd:                   # Path to the local script to run followed by optional arguments.
      creates:               # A filename on the remote node, when it already exists, this step will *not* be run.
      decrypt:               # This option controls the autodecryption of source files using vault.
      executable:            # Name or path of a executable to invoke the script with.
      free_form:             # Path to the local script file followed by optional arguments.
      removes:               # A filename on the remote node, when it does not exist, this step will *not* be run.

范例 :

[root@ansible ~]#ansible websrvs -m script -a /data/test.sh
3.4.4 Copy模块

功能:从ansible服务器主控端复制文件到远程主机

#如目标存在,默认覆盖,此处指定先备份
ansible websrvs -m copy -a "src=/root/test1.sh dest=/tmp/test2.sh   owner=wang
mode=600 backup=yes"
#指定内容,直接生成目标文件    
ansible websrvs -m copy -a "content='test line1\ntest line2' dest=/tmp/test.txt"
#复制/etc目录自身,注意/etc/后面没有/
ansible websrvs -m copy -a "src=/etc dest=/backup"
#复制/etc/下的文件,不包括/etc/目录自身,注意/etc/后面有/
ansible websrvs -m copy -a "src=/etc/ dest=/backup"
3.4.5 Fetch模块

功能:从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录

模块说明

#fetch模块说明
[root@ansible ~]#ansible-doc -s fetch
- name: Fetch files from remote nodes
  fetch:
      dest:                  # (required) A directory to save the file into. For example, if the `dest' directory is
                               `/backup' a `src' file named `/etc/profile' on host
                               `host.example.com', would be saved into
                               `/backup/host.example.com/etc/profile'. The host name
                               is based on the inventory name.
      fail_on_missing:       # When set to `yes', the task will fail if the remote file cannot be read for any
                               reason. Prior to Ansible 2.5, setting this would only
                               fail if the source file was missing. The default was
                               changed to `yes' in Ansible 2.5.
      flat:                  # Allows you to override the default behavior of appending hostname/path/to/file to the
                               destination. If `dest' ends with '/', it will use the
                               basename of the source file, similar to the copy
                               module. This can be useful if working with a single
                               host, or if retrieving files that are uniquely named
                               per host. If using multiple hosts with the same
                               filename, the file will be overwritten for each host.
      src:                   # (required) The file on the remote system to fetch. This `must' be a file, not a
                               directory. Recursive fetching may be supported in a
                               later release.
      validate_checksum:     # Verify that the source and destination checksums match after the files are fetched.

范例:

[root@ansible ~]#ansible websrvs -m fetch -a 'src=/root/test.sh dest=/data/scripts'

范例:

[root@ansible ~]#ansible   all -m fetch -a 'src=/etc/redhat-release
dest=/data/os'
[root@ansible ~]#tree /data/os/
/data/os/
├── 10.0.0.6
│   └── etc
│       └── redhat-release
├── 10.0.0.7
│   └── etc
│       └── redhat-release
└── 10.0.0.8
   └── etc
       └── redhat-release

6 directories, 3 files
3.4.6 File模块

功能:设置文件属性

模块说明

[root@ansible ~]#ansible-doc -s file
- name: Manage files and file properties
  file:
      access_time:           # This parameter indicates the time the file's access time                                  should be set to. Should be
                               `preserve' when no modification is required,
                               `YYYYMMDDHHMM.SS' when using default time format, or
                               `now'. Default is `None' meaning that `preserve' is the
                               default for `state=[file,directory,link,hard]' and
                               `now' is default for `state=touch'.
      access_time_format:    # When used with `access_time', indicates the time format                                that must be used. Based on
                               default Python format (see time.strftime doc).
      attributes:            # The attributes the resulting file or directory should                                      have. To get supported flags
                               look at the man page for `chattr' on the target system.
                               This string should contain the attributes in the same
                               order as the one displayed by `lsattr'. The `='
                               operator is assumed as default, otherwise `+' or `-'
                               operators need to be included in the string.
      follow:                # This flag indicates that filesystem links, if they exist,                                 should be followed. Previous
                               to Ansible 2.5, this was `no' by default.
      force:                 # Force the creation of the symlinks in two cases: the                                       source file does not exist (but
                               will appear later); the destination exists and is a
                               file (so, we need to unlink the `path' file and create
                               symlink to the `src' file in place of it).
      group:                 # Name of the group that should own the file/directory, as                                  would be fed to `chown'.
      mode:                  # The permissions the resulting file or directory should                                     have. For those used to
                               `/usr/bin/chmod' remember that modes are actually octal
                               numbers. You must either add a leading zero so that
                               Ansible's YAML parser knows it is an octal number (like
                               `0644' or `01777') or quote it (like `'644'' or
                               `'1777'') so Ansible receives a string and can do its
                               own conversion from string into number. Giving Ansible
                               a number without following one of these rules will end
                               up with a decimal number which will have unexpected
                               results. As of Ansible 1.8, the mode may be specified
                               as a symbolic mode (for example, `u+rwx' or
                               `u=rw,g=r,o=r'). As of Ansible 2.6, the mode may also
                               be the special string `preserve'. When set to
                               `preserve' the file will be given the same permissions
                               as the source file.
      modification_time:     # This parameter indicates the time the file's modification                              time should be set to.
                               Should be `preserve' when no modification is required,
                               `YYYYMMDDHHMM.SS' when using default time format, or
                               `now'. Default is None meaning that `preserve' is the
                               default for `state=[file,directory,link,hard]' and
                               `now' is default for `state=touch'.
      modification_time_format:   # When used with `modification_time', indicates the                                     time format that must be used. >
                               on default Python format (see time.strftime doc).
      owner:                 # Name of the user that should own the file/directory, as                                   would be fed to `chown'.
      path:                  # (required) Path to the file being managed.
      recurse:               # Recursively set the specified file attributes on directory                                contents. This applies only
                               when `state' is set to `directory'.
      selevel:               # The level part of the SELinux file context. This is the                                   MLS/MCS attribute, sometimes
                               known as the `range'. When set to `_default', it will
                               use the `level' portion of the policy if available.
      serole:                # The role part of the SELinux file context. When set to                                     `_default', it will use the
                               `role' portion of the policy if available.
      setype:                # The type part of the SELinux file context. When set to                                    `_default', it will use the
                               `type' portion of the policy if available.
      seuser:                # The user part of the SELinux file context. By default it                                  uses the `system' policy,
                               where applicable. When set to `_default', it will use
                               the `user' portion of the policy if available.
      src:                   # Path of the file to link to. This applies only to                                        `state=link' and `state=hard'. For
                               `state=link', this will also accept a non-existing
- name: Manage files and file properties
  file:
      access_time:           # This parameter indicates the time the file's access time                                  should be set to. Should be
                               `preserve' when no modification is required,
                               `YYYYMMDDHHMM.SS' when using default time format, or
                               `now'. Default is `None' meaning that `preserve' is the
                               default for `state=[file,directory,link,hard]' and
                               `now' is default for `state=touch'.
      access_time_format:    # When used with `access_time', indicates the time format                                  that must be used. Based on
                               default Python format (see time.strftime doc).
      attributes:            # The attributes the resulting file or directory should                                    have. To get supported flags
                               look at the man page for `chattr' on the target system.
                  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值