【发布时间】:2016-03-02 16:14:33
【问题描述】:
我正在尝试自己在 ansible 上速成课程...而且我遇到了需要将文件导入 postgres 的情况。 ansible 的 postgres 模块没有 mysql 模块的所有命令......所以我不得不找到另一种方法来对 db 运行 sql 命令。
我正在使用 shell 命令。但是,我不知道如何检查 shell 命令是否成功。
这是我的剧本到目前为止的样子:
- hosts: webservers
tasks:
- block:
- debug: msg='Start sql insert play...'
- copy: src=file.dmp dest=/tmp/file.dmp
- debug: msg='executing sql file...'
- shell: psql -U widgets widgets < /tmp/file.dmp
- debug: msg='all is well'
when: result|succeeded
rescue:
- debug: msg='Error'
always:
- debug: msg='End of Play'
# - block:
# - name: restart secondarywebservers
# - debug: msg='Attempting to restart secondary servers'
# - hosts: websecondaries
我最终想要做的是只有在第一个代码块成功时才开始第二个代码块。现在,只是为了了解条件是如何工作的,我正在尝试查看当我确定执行了 sql 文件时是否可以在屏幕上打印一条消息。
它失败并显示以下错误消息:
TASK [debug] *******************************************************************
fatal: [10.1.1.109]: FAILED! => {"failed": true, "msg": "The conditional check 'result|succeeded' failed. The error was: |failed expects a dictionary\n\nThe error appears to have been in '/etc/ansible/playbooks/dbupdate.yml': line 9, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n - shell: psql -U openser openser < /tmp/file.dmp\n - debug: msg='all is well'\n ^ here\n"}
我仍在研究条件语句的工作原理……所以可能是我的语法错误。但更大的问题是——由于没有原生 ansible / postgresql 导入命令,我意识到 ansible 无法知道“file.dmp”中的命令确实创建了我的数据库记录...... 我可以在 file.dmp 中添加一个 select 语句来尝试选择我刚刚创建的记录...但是我如何将它传递回 ansible?
只是想知道是否有人对我如何完成这样的事情有一些想法。
谢谢。
编辑 1
以下是测试“file.dmp”的内容:
INSERT INTO mytable VALUES (DEFAULT, 64, 1, 1, 'test', 0, '^(.*)$', '\1);
编辑 2
我将尝试做这样的事情:
Copy (Select * From mytable where ppid = 64) To '/tmp/test.csv' With CSV;
在插入语句之后...然后对该文件进行 ansible 检查(可能使用 lineinfile 命令)作为向自己证明插入有效的一种方式。
【问题讨论】:
-
您需要“注册”结果变量,以便在检查中使用它。 docs.ansible.com/ansible/…
-
@Petro026 谢谢。解决了语法错误...但是通过 shell 命令导入 file.dmp 文件不会返回结果。这就是我要解决的真正问题。请参阅我的编辑#2。
-
嗯,psql 是一个 CLI 实用程序。因此,您在捕获返回状态方面受到限制。两个基本选项是检查 shell 返回代码 (result.rc) 或查看标准输出是否有肯定的指示 (result.stdout)。如果你想检查状态为什么不直接用shell模块执行一个查询,即psql -c 'select id, from mytable where ppid=64,然后看看结果。我在我们的 oracle 环境中使用带有 shell 模块的 sqlplus 和类似的东西。
-
@Petro026,是的,我们在同一页上。我可以从命令行运行另一个 sql 命令,或者在 file.dmp 中包含一些逻辑来创建一个输出文件,其中包含结果。
-
如果您要将文件写入机器并在其中查找状态,这也可能对您有所帮助。 docs.ansible.com/ansible/wait_for_module.html
标签: postgresql ansible ansible-playbook