描述

  幂等性是在实际应用中经常需要考虑的概念,尤其是运维中。相较于将幂等性理解为各种异常情况的综合处理,将其理解为执行时需要考虑到在前次执行产生的影响的情况下能够正常执行则会更加容易接近业务需求。

  ansible包含众多的模块,大部分内置模块都能够保证操作的幂等性,即相关操作的多次执行能够达到相同结果这一特性,不会出现多次执行带来副作用的影响。但是也有不满足幂等原则的,比如shell模块、raw模块、command模块。

幂等操作和非幂等操作的对比

场景说明:

比如实现删除一个临时性的文件/root/testfile的操作,如果希望其在相同的条件下,多次执行能够保持相同的结果和不会带来其它副作用,至少需要保证此操作在/root/testfile文件存在和不存在的情况下都能正常动作。

# 当采用raw模块执行shell命令删除文件,第一次删除是成功,当执行第二次删除也是成功的,但是在生产环境这结果是不理想的,比如重启一个服务,你会随便重复重启吗?

[root@Server-1~]# touch /root/testfile
[root@Server-1~]# ansible localhost -m shell -a "rm -rf testfile"
localhost | CHANGED | rc=0 >>
[root@Server-1~]# ansible localhost -m shell -a "rm -rf testfile"
localhost | CHANGED | rc=0 >>

# 当采用file 模块执行删除文件,第一次执行删除文件成功changed: true,多次执行删除文件都是同一样的结果,不会带来副作用的影响changed: Fasle

[root@Server-1~]# touch /root/testfile
[root@Server-1~]# ansible localhost -m file -a "path=/root/testfile state=absent"
localhost | CHANGED => {
"changed": true,
"path": "/root/testfile",
"state": "absent"
}
[root@Server-1~]# ansible localhost -m file -a "path=/root/testfile state=absent"
localhost | SUCCESS => {
"changed": false,
"path": "/root/testfile",
"state": "absent"
}
贴上file模块absent时文件实现的幂等(中文注释)

vim /usr/lib/python2.7/site-packages/ansible/modules/files/file.py
.....
def get_state(path):
''' Find out current state ''' b_path = to_bytes(path, errors='surrogate_or_strict')
try:
if os.path.lexists(b_path): # 如果文件存在返回file,文件不存在返回absent
if os.path.islink(b_path):
return 'link'
elif os.path.isdir(b_path):
return 'directory'
elif os.stat(b_path).st_nlink > 1:
return 'hard' # could be many other things, but defaulting to file
return 'file' return 'absent'
except OSError as e:
if e.errno == errno.ENOENT: # It may already have been removed
return 'absent'
else:
raise def ensure_absent(path):
b_path = to_bytes(path, errors='surrogate_or_strict')
prev_state = get_state(b_path) # 获取文件的状态
result = {} if prev_state != 'absent': # 当prev_state='directory' or 'file' 为真
diff = initial_diff(path, 'absent', prev_state) if not module.check_mode:
if prev_state == 'directory': # 如果prev_state='directory', 则删除目录
try:
shutil.rmtree(b_path, ignore_errors=False)
except Exception as e:
raise AnsibleModuleError(results={'msg': "rmtree failed: %s" % to_native(e)})
else:
try:
os.unlink(b_path) # 如果prev_state='file', 则删除文件
except OSError as e:
if e.errno != errno.ENOENT: # It may already have been removed
raise AnsibleModuleError(results={'msg': "unlinking failed: %s " % to_native(e),
'path': path}) result.update({'path': path, 'changed': True, 'diff': diff, 'state': 'absent'}) # 删除文件成功,动作有改变,changed=True
else:
result.update({'path': path, 'changed': False, 'state': 'absent'}) # 如果prev_state='absent', 动作没有改变,changed=False, 实现多次操作执行不会有任何改变。 return result def main(): global module module = AnsibleModule(
argument_spec=dict(
state=dict(type='str', choices=['absent', 'directory', 'file', 'hard', 'link', 'touch']),
path=dict(type='path', required=True, aliases=['dest', 'name']),
_original_basename=dict(type='str'), # Internal use only, for recursive ops
recurse=dict(type='bool', default=False),
force=dict(type='bool', default=False), # Note: Should not be in file_common_args in future
follow=dict(type='bool', default=True), # Note: Different default than file_common_args
_diff_peek=dict(type='bool'), # Internal use only, for internal checks in the action plugins
src=dict(type='path'), # Note: Should not be in file_common_args in future
modification_time=dict(type='str'),
modification_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),
access_time=dict(type='str'),
access_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),
),
add_file_common_args=True,
supports_check_mode=True,
) # When we rewrite basic.py, we will do something similar to this on instantiating an AnsibleModule
sys.excepthook = _ansible_excepthook
additional_parameter_handling(module.params)
params = module.params state = params['state']
recurse = params['recurse']
force = params['force']
follow = params['follow']
path = params['path']
src = params['src'] timestamps = {}
timestamps['modification_time'] = keep_backward_compatibility_on_timestamps(params['modification_time'], state)
timestamps['modification_time_format'] = params['modification_time_format']
timestamps['access_time'] = keep_backward_compatibility_on_timestamps(params['access_time'], state)
timestamps['access_time_format'] = params['access_time_format'] # short-circuit for diff_peek
if params['_diff_peek'] is not None:
appears_binary = execute_diff_peek(to_bytes(path, errors='surrogate_or_strict'))
module.exit_json(path=path, changed=False, appears_binary=appears_binary) if state == 'file':
result = ensure_file_attributes(path, follow, timestamps)
elif state == 'directory':
result = ensure_directory(path, follow, recurse, timestamps)
elif state == 'link':
result = ensure_symlink(path, src, follow, force, timestamps)
elif state == 'hard':
result = ensure_hardlink(path, src, follow, force, timestamps)
elif state == 'touch':
result = execute_touch(path, follow, timestamps)
elif state == 'absent':
result = ensure_absent(path) # 执行删除文件时,调用方法 def ensure_absent module.exit_json(**result) if __name__ == '__main__':
main()

[自动化]浅聊ansible的幂等的更多相关文章

  1. 自动化运维 Ansible

    自动化运维 Ansible 特性 (1).no agents:不需要在被管控主机上安装任何客户端: (2).no server:无服务器端,使用时直接运行命令即可: (3).modules in an ...

  2. 浅聊ARP

    今天借用思科公司的Cisco Packet Tracer Student这款软件浅聊ARP 什么是ARP? ARP即地址解析协议(Address Resolution Protocol),是根据Ip地 ...

  3. 自动化运维Ansible安装篇

    Ansible自动化工具之--部署篇 ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func.fabric)的优点,实现了 ...

  4. 自动化运维-ansible入门篇

    1.ansible配置 什么是Ansible IT自动化工具 依赖于现有的操作系统凭证来访问控制远程机器 简单易用.安全可靠 Ansible可以完成哪些任务 配置系统 开发软件 编排高级的IT任务 A ...

  5. 运维自动化之1 - ansible 批量主机管理

    2000 - 2016 年,维护的小型机.linux刚开始的2台增加到上千台,手工检查.日常版本升级需要管理太多设备,必须通过运维自动化实现 特别是版本升级,需要到同类机器部署代码.起停设备,必须在一 ...

  6. 服务器/网络/虚拟化/云平台自动化运维-ansible

    ansible与netconf的对比 首先明确一个概念,netconf是协议,ansible是python编写的工具 netconf 使用YANG建模,XML进行数据填充,使用netconf协议进行传 ...

  7. Jenkins+Ansible+Gitlab自动化部署三剑客-Ansible本地搭建

    可以通过git bash连接linux 关闭防火墙,禁用防火墙开机启动,并更爱selinux文件,重启 重新登录并检查禁用 getenforce 安装git yum -y install git ns ...

  8. Python自动化运维ansible从入门到精通

    1. 下载安装 在windows下安装ansible:

  9. 自动化运维—Ansible(上)

    一:为什么选择Ansible 相对于puppet和saltstack,ansible无需客户端,更轻量级 ansible甚至都不用启动服务,仅仅只是一个工具,可以很轻松的实现分布式扩展 更强的远程命令 ...

随机推荐

  1. centos,fedora,ubuntu,opensuse感想

    最先接触的是ubuntu,貌似身边同学用的最多,出了什么问题,网上解决方法也很多,但是后来学鸟哥私房菜,就按照他说的在实验室电脑装了一个centos,果然为服务器而生,稳定得很,界面朴素,装日常软件比 ...

  2. golang中goroutine池的使用

    1. 概念本质上是生产者.消费者模型可以有效的控制goroutine数量,防止暴涨案例:生成一个随机数,计算该随机数每一个数字相加的和,例如:123:1+2+3=6主协程负责生产数据发送到待处理通道中 ...

  3. java-异常-异常应用

    1 package p1.exception; 2 3 4 /* 5 * 老师用电脑上课. 6 * 7 * 问题领域中涉及两个对象. 8 * 老师,电脑. 9 * 10 * 分析其中的问题. 11 * ...

  4. UncLutter

    在 Mac 上「速记」的正确姿势:Unclutter 现代人的大脑,每天都会被大量有用,或无用的东西充斥着,过多「思想垃圾」的沉重负担就容易导致失忆.也就是说,你很可能会记得一个无关紧要,但给你留下深 ...

  5. Linux 配置 dubbo 和 dubbo的简单介绍。

    一.是么是  dubbo? 一.dubbo? 1.因为项目之间需要相互调用,达到某种预期的结果 1.1 restful? 门户网站必须要知道用户的登录状态,但是用户的登录状态在登录项目中,所以门户网站 ...

  6. Linux下的5种I/O模型与3组I/O复用

    引言 上一篇文章中介绍了一些无缓冲文件I/O函数,但应该什么时机调用这些函数,调用这些I/O函数时进程和内核的行为如何,如何高效率地实现I/O?这篇文章就来谈一谈Linux下的5种I/O模型,以及高性 ...

  7. java基础之抽象类的介绍

    抽象类的特点: 1.当方法只有声明没有具体实现的时候,需要用abstract修饰符修饰.抽象方法必须定义在抽象类当中,所以抽象类也需要用abstract修饰 2.抽象类不可以被实例化,为什么呢?   ...

  8. Visual Studio 下error C2471: 无法更新程序数据库

    转载请注明来源:https://www.cnblogs.com/hookjc/ 解决方案:修改项目属性 右击项目 --> "属性" 1. "C/C++" ...

  9. Jmeter平均响应时间和TPS的计算方法

    转自:https://www.cnblogs.com/xianlai-huang/p/7795215.html Jmeter的Throughput和平均RT的计算 1.TPS:每秒处理的事务数,jme ...

  10. 把 Navigation Bar 下面那条线删掉的最简单的办法! — By: 昉

    系统默认的 Navigation Bar 下面一直有条线,翻尽了文档却没找到能把它弄走的相关接口,处女座的简直木法忍啊有木有!!!! 研究了一下navigationBar下的子视图,原来只需要几行代码 ...