Cloudify Manager中Python脚本如何获取配置文件路径?
解决Cloudify部署中脚本无法访问同目录配置文件的问题
在Cloudify部署场景下,你的python_script.py和sample.conf原本同属蓝图的scripts目录,但部署时脚本会被复制到临时执行目录,导致相对路径无法找到原配置文件。可以通过Cloudify提供的上下文API解决这个问题:
核心解决方案
利用Cloudify的ctx.download_resource()方法,直接从蓝图资源中获取sample.conf的正确路径,无需关心部署时的临时解压位置。
修改后的脚本代码
import configparser from cloudify import ctx from cloudify.state import ctx_parameters as inputs import os print("Path at terminal when executing this file") print(os.getcwd() + "\n") print("This file path, relative to os.getcwd()") print(__file__ + "\n") print("The directory is ") print(os.path.dirname(__file__) + "\n") # 关键修改:从蓝图资源中下载sample.conf到临时目录 sample_conf_path = ctx.download_resource('scripts/sample.conf') parser = configparser.ConfigParser() parser.read(sample_conf_path) # 现在可正确读取配置文件 configer = configparser.ConfigParser() # 你的解析逻辑写在这里 with open(r"/tmp/new.conf", 'w+') as configfile: configer.write(configfile, True)
原理说明
ctx.download_resource()接收的参数是相对于蓝图根目录的资源路径(此处为scripts/sample.conf,匹配你的蓝图目录结构)。- Cloudify会自动处理蓝图资源的存储与定位,将指定文件下载到脚本执行的临时目录,并返回本地文件路径供调用。
内容的提问来源于stack exchange,提问作者Kasibak
相关产品推荐
相关产品推荐

