浅聊ansible的幂等 file模块源码解析

2024-01-26 16:20

本文主要是介绍浅聊ansible的幂等 file模块源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

描述#

  幂等性是在实际应用中经常需要考虑的概念,尤其是运维中。相较于将幂等性理解为各种异常情况的综合处理,将其理解为执行时需要考虑到在前次执行产生的影响的情况下能够正常执行则会更加容易接近业务需求。
  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模块是如何实现幂等的呢?如下是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,文件不存在返回absentif 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 filereturn 'file' return 'absent'except OSError as e:if e.errno == errno.ENOENT:  # It may already have been removedreturn 'absent'else:raisedef 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 removedraise AnsibleModuleError(results={'msg': "unlinking failed: %s " % to_native(e),'path': path})result.update({'path': path, 'changed': True, 'diff': diff, 'state': 'absent'}) # 删除文件成功,动作有改变,changed=Trueelse:result.update({'path': path, 'changed': False, 'state': 'absent'}) # 如果prev_state='absent', 动作没有改变,changed=False, 实现多次操作执行不会有任何改变。return resultdef main():global modulemodule = 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 opsrecurse=dict(type='bool', default=False),force=dict(type='bool', default=False),  # Note: Should not be in file_common_args in futurefollow=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 pluginssrc=dict(type='path'),  # Note: Should not be in file_common_args in futuremodification_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 AnsibleModulesys.excepthook = _ansible_excepthookadditional_parameter_handling(module.params)params = module.paramsstate = 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_peekif 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_absentmodule.exit_json(**result)if __name__ == '__main__':main()

这篇关于浅聊ansible的幂等 file模块源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/647364

相关文章

解决JavaWeb-file.isDirectory()遇到的坑问题

《解决JavaWeb-file.isDirectory()遇到的坑问题》JavaWeb开发中,使用`file.isDirectory()`判断路径是否为文件夹时,需要特别注意:该方法只能判断已存在的文... 目录Jahttp://www.chinasem.cnvaWeb-file.isDirectory()遇

C语言中自动与强制转换全解析

《C语言中自动与强制转换全解析》在编写C程序时,类型转换是确保数据正确性和一致性的关键环节,无论是隐式转换还是显式转换,都各有特点和应用场景,本文将详细探讨C语言中的类型转换机制,帮助您更好地理解并在... 目录类型转换的重要性自动类型转换(隐式转换)强制类型转换(显式转换)常见错误与注意事项总结与建议类型

Python利用自带模块实现屏幕像素高效操作

《Python利用自带模块实现屏幕像素高效操作》这篇文章主要为大家详细介绍了Python如何利用自带模块实现屏幕像素高效操作,文中的示例代码讲解详,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、获取屏幕放缩比例2、获取屏幕指定坐标处像素颜色3、一个简单的使用案例4、总结1、获取屏幕放缩比例from

MySQL 缓存机制与架构解析(最新推荐)

《MySQL缓存机制与架构解析(最新推荐)》本文详细介绍了MySQL的缓存机制和整体架构,包括一级缓存(InnoDBBufferPool)和二级缓存(QueryCache),文章还探讨了SQL... 目录一、mysql缓存机制概述二、MySQL整体架构三、SQL查询执行全流程四、MySQL 8.0为何移除查

nginx-rtmp-module模块实现视频点播的示例代码

《nginx-rtmp-module模块实现视频点播的示例代码》本文主要介绍了nginx-rtmp-module模块实现视频点播,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习... 目录预置条件Nginx点播基本配置点播远程文件指定多个播放位置参考预置条件配置点播服务器 192.

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

使用Java实现一个解析CURL脚本小工具

《使用Java实现一个解析CURL脚本小工具》文章介绍了如何使用Java实现一个解析CURL脚本的工具,该工具可以将CURL脚本中的Header解析为KVMap结构,获取URL路径、请求类型,解析UR... 目录使用示例实现原理具体实现CurlParserUtilCurlEntityICurlHandler

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC