2017-08-09 186 views
0

我想使用下面的命令從我的pom.xml返回版本,但它不起作用。在Ansible playbook中使用sed命令

- name: ensure apache is at the latest version 
    shell: "echo cat \/\/*[local-name()='project']\/*[local-name()='version'] | xmllint --shell pom.xml | sed '\/^\/ >/d' | sed 's/<[^>]*.//g'" 
    register: ArtifactId 
- debug: var=ArtifactId.stdout_lines 

有人可以幫忙嗎?

+0

你得到的錯誤是什麼? –

回答

2

這是更基本的殼問題,而不是一個Ansible問題。該命令行產生一個錯誤,即使沒有ansible:

$ echo cat \/\/*[local-name()='project']\/*[local-name()='version'] | xmllint --shell pom.xml | sed '\/^\/ >/d' | sed 's/<[^>]*.//g' 
bash: syntax error near unexpected token `(' 

cat命令的參數不充分引述的,你可能在漏出的是不必要的正斜槓(/),並且可實際上導致問題。試試這個:

- hosts: localhost 
    tasks: 
    - shell: > 
     echo cat '//*[local-name()="project"]/*[local-name()="version"]' | 
     xmllint --shell pom.xml | 
     sed '\/^\/ >/d' | 
     sed 's/<[^>]*.//g' 
     register: artifactId 

    - debug: 
     var: artifactId.stdout_lines 

使用>折標量運算符可以讓你避免報價的水平,這使得命令更易於管理。它還允許您將其格式化爲更具可讀性。

鑑於以下輸入:

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <version>4.0.0</version> 
</project> 

以上劇本的結果:

TASK [command] ***************************************************************** 
changed: [localhost] 

TASK [debug] ******************************************************************* 
ok: [localhost] => { 
    "artifactId.stdout_lines": [ 
     "4.0.0" 
    ] 
} 

雖然這工作,你可能要考慮使用某種XPath的模塊爲ansible代替。 This one似乎有最近的活動,雖然我沒有嘗試過自己。

+0

它的工作謝謝^^ –

+1

我有Debian中測試,但它打印不同勢結果與2行: '確定:[本地主機] => { 「artifactId.stdout_lines」:[ 「------ - 「, 」0.1.0-SNAPSHOT「 ] }' – Gimbo

+0

這聽起來像是你現在可能只需要修復XPath表達式。 如果您想用可重現的示例(可運行的playbook *和*相應的'pom.xml'來更新您的問題,那麼會導致所描述的行爲),我很樂意仔細查看。 – larsks