ansible 从标准输出解析文本字符串 [英] ansible parse text string from stdout
问题描述
我的问题是 ansible 和解析标准输出.我需要从 ansible play 中捕获 stdout 并解析此输出以获取 stdout 中的特定子字符串并保存到 var 中.我的具体用例如下
My problem is with ansible and parsing stdout. I need to capture the stdout from an ansible play and parse this output for a specific substring within stdout and save into a var. My specific use case is below
- shell: "vault.sh --keystore EAP_HOME/vault/vault.keystore |
--keystore-password vault22 --alias vault --vault-block |
vb --attribute password --sec-attr 0penS3sam3 --enc-dir |
EAP_HOME/vault/ --iteration 120 --salt 1234abcd"
register: results
become: true
这会生成一个带有以下行的输出,目标是捕获 jboss vault 生成的掩码密钥并将其保存在 ansible var 中,以便我可以使用它来配置 standalone.xml 模板:
This generates an output with the following line, the goal is to capture the masked key that jboss vault generates and save that in an ansible var so I can use it to configure the standalone.xml template:
vault-option name="KEYSTORE_PASSWORD" value="MASK-5dOaAVafCSd"/>
我需要一种可能使用正则表达式解析此字符串的方法,并使用 set_facts 模块或任何其他 ansible 模块将MASK-5dOaAVafCSd"子字符串保存到 ansible var 中.
I need a way parse this string with possibly regex and save the "MASK-5dOaAVafCSd" substring into an ansible var using set_facts module or any other ansible module.
目前我的代码是这样的
#example stdout
results: vault-option name=\"KEYSTORE_PASSWORD\" value=\"MASK-5dOaAVafCSd\"/>
- name: JBOSS_VAULT:define keystore password masked value variable
set_fact:
masked_value: |
"{{ results.stdout |
regex_replace('^.+(MASK-.+?)\\.+','\\\1') }}"
此代码将 masked_value 定义为 results.stdout
,而不是预期的捕获组.
This code is defining masked_value as the results.stdout
, not the expected capture group.
推荐答案
你们很亲近.我建议您使用 regex101.com 来测试正则表达式.
You are very close. I advice you to use regex101.com to test regular expressions.
这是我的解决方案:
---
- hosts: localhost
gather_facts: no
tasks:
- shell: echo 'vault-option name="KEYSTORE_PASSWORD" value="MASK-5dOaAVafCSd"'
register: results
- set_fact:
myvalue: "{{ results.stdout | regex_search(regexp,'\\1') }}"
vars:
regexp: 'value=\"([^"]+)'
- debug:
var: myvalue
结果:
ok: [localhost] => {
"myvalue": [
"MASK-5dOaAVafCSd"
]
}
更新:
regex_search
返回找到的匹配列表,因此只获取第一个使用:
regex_search
returns a list of found matches, so to get only first one use:
{{ results.stdout | regex_search(regexp,'\\1') | first }}
这篇关于ansible 从标准输出解析文本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!