完整的代码已经在github开源:github.com/CTC-maxiao/…python
ansible的一些基础配置信息保存在ansible.cfg文件中,包括ssh链接的默认host,默认port等。以前咱们设计的程序是先从配置文件中读取信息,而后添加到执行字典中。为了方便读写,咱们以json文件来保存配置信息。python读写json文件很是简单,只须要使用json库。git
def read_cfg_file(cfg_file):
if os.path.isfile(cfg_file):
with open(cfg_file,"r") as f:
file_content = json.load(f)
if file_content:
return file_content
else:
print "config file format error"
sys.exit(1)
else:
print "config file not existed"
sys.exit(1)
复制代码
playbook是ansible的精髓所在,python读写yaml文件也是很是简单便捷的,只须要使用yaml库。github
def read_yaml_file(filename):
if os.path.isfile(filename):
with open(filename,"r") as f:
file_content = yaml.load(f)
if file_content:
return file_content
else:
print "yaml file format error"
sys.exit(1)
else:
print "yaml file not existed"
sys.exit(1)
复制代码
读取后的结果是一个只有一个字典元素的list,咱们直接能够经过read_yaml_file()[0]来获取这个字典元素。json
一般一个playbook中包含多个task。在读取yaml文件生成的字典中,这些task以字典形式保存在一个list中。因此咱们能够先将配置文件和yaml文件中除task部分的内容填入到临时字典中,而后将分别将task字典中的内容填入临时字典,而后将临时字典中的内容保存到一个list里,这样就得到了最终的task执行列表。bash
def get_final_task_list(ssh_user,ssh_pwd,yaml_file):
cfg_dict = read_cfg_file()
yaml_dict = read_yaml_file(yaml_file)[0]
final_task_list=[]
for key,value in cfg_dict.items(): #将配置文件中的内容填入到模板字典中
if template_dict.has_key(key):
template_dict[key] = value
for key,value in yaml_dict.items(): #将yaml文件中除task部分外的内容填入到模板字典中
if template_dict.has_key(key):
if key != "tasks":
self.template_dict[key] = value
template_dict["ssh_user"] = ssh_user #将ssh的用户和密码填入到模板字典中
template_dict["ssh_pwd"] = ssh_pwd
for task_dict in yaml_dict["tasks"]:
tmp_dict = {}
tmp_dict = template_dict.copy() #将模板字典复制到临时字典中
for key,value in task_dict.items():
if tmp_dict.has_key(key):
tmp_dict[key] = value #将yaml文件中task部分分别填入到临时字典中
if "delegate_to" in task_dict.keys():
tmp_dict["task_host"] = task_dict["delegate_to"] #处理delegate_to关键字,赋值给task_host
final_task_list.append(tmp_dict.copy()) #将临时字典的浅拷贝添加到最终的执行列表中
return final_task_list
复制代码
其中template_dict就是咱们在第一节中设计的执行字典,格式以下:app
template_dict={
"task_name": "",
"task_host": "",
"become": "",
"become_method": "",
"become_user": "",
"become_pwd": "",
"ssh_user": "",
"ssh_pwd": "",
"register": "",
"action_type": "",
"action": ""
}
复制代码
在写好这些代码以后,只须要调用get_final_task_list()函数,传入ssh登陆的用户和密码,以及要使用的yaml文件后,就获得了最终的执行字典列表。ssh