2016-03-02 155 views
0

我試圖在ansible上崩潰當然我自己...我遇到了一個場景,我需要將文件導入到postgres中。用於ansible的postgres模塊沒有mysql模塊所有的命令......所以我必須找到另一種方法來針對db運行sql命令。ansible - 如何檢查導入sql文件到postgres的成功

我正在使用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導入命令,我意識到沒有辦法可以知道「file.dmp」中的命令真的創建了我的數據庫記錄...... 我可以添加一個選擇file.dmp中的語句來嘗試選擇我剛剛創建的記錄...但是,如何將它傳遞給ansible?

只是想知道如果有人對我如何能完成這樣的事情有一些想法。

謝謝。

編輯1

下面是測試 「file.dmp」 的內容包括:

INSERT INTO mytable VALUES (DEFAULT, 64, 1, 1, 'test', 0, '^(.*)$', '\1); 

EDIT 2

我要去嘗試做一些事情像這樣:

複製(選擇* from mytable ppid = 64)到'/ tmp/test。 csv'帶CSV;

在插入語句之後...然後對此文件(可能使用lineinfile命令)進行檢查以證明插入的工作方式。

+0

您需要「註冊」的結果變量,因此您可以在您的支票使用它。 http://docs.ansible.com/ansible/playbooks_variables.html#registered-variables – Petro026

+0

@ Petro026謝謝。解決語法錯誤...但通過shell命令導入file.dmp文件不會返回結果。這是我試圖解決的真正問題。請參閱我的編輯#2。 – dot

+0

那麼,psql是一個CLI實用程序。因此,您在捕獲退貨狀態方面受到限制。兩個基本選項是檢查shell返回碼(result.rc)或查看stdout以獲取正確指示(result.stdout)。如果你想檢查狀態,爲什麼不用shell模塊執行一個查詢,即psql -c'select id,從ptable = 64的mytable中查看結果。我在我們的oracle環境中使用了與shell模塊相似的sqlplus。 – Petro026

回答

0

你只需要register那個結果變量。

改變你的遊戲看起來像這應該工作:

- 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 
     register: result 
    - debug: msg='all is well' 
     when: result|succeeded 
    rescue: 
     - debug: msg='Error' 
    always: 
     - debug: msg='End of Play' 
+0

謝謝。答案/解決了我的語法問題......但我想我仍然需要一種方法來「證明」sql輸入文件是合法的/工作的。我將嘗試運行轉儲到文件的後續sql select語句,然後檢查文件的存在。 – dot