sed 替换中的嵌套命令

sed 替换中的嵌套命令

我尝试sed查找和ansible_password加密库存文件中的字段,并使用ansible-vault命令对其进行加密。但ansible-command失败并引发sed错误,而简单的 echo 则工作正常。

sed -n "s/\( *\)\(ansible_password\: *\)\"\(.*\)\"/$(echo \\3)/p" sample.yml

输出不带双引号的属性值。

命令ansible-vault

sed -n "s/\( *\)\(ansible_password\: *\)\"\(.*\)\"/$(ansible-vault encrypt_string --vault-password-file ~/password.txt --name 'ansible_password' '\\3')/p" sample.yml

抛出错误信息:sed: -e expression #1, char 67: unterminated ``s' command

以下是发生替换的行:

        ansible_password: "somepassword"

答案1

这行不通。嵌套命令将首先运行。echo偶然会起作用,因为它会将其\3作为替换模式,而这恰好是您在本例中想要的(= 输出原始值)。

不确定你到底想要什么,也许你可以grep尝试xargs

grep -Po 'ansible_password: \K"[^"]*' sample.yaml \
| xargs -n1 ansible-vault encrypt_string --vault-password-file ~/password.txt --name 'ansible_password'

不过,你可能需要使用适当的yaml解析器而不是grepsed

答案2

使用阻止文件如果你可以将变量放入“# BEGIN ... # END”块中,例如

shell> cat sample.yml
# BEGIN my_password1
my_password1: "somepassword1"
# END my_password1
# BEGIN my_password2
my_password2: "somepassword2"
# END my_password2
# BEGIN my_password3
my_password3: "somepassword3"
# END my_password3

然后下面的任务读取文件并用加密变量替换块,例如

    - include_vars:
        file: sample.yml
        name: my_pswd
    - blockinfile:
        dest: sample.yml
        marker: "# {mark} {{ item }}"
        block: "{{ _enc }}"
      loop: [my_password1, my_password2, my_password3]
      vars:
        vault_cmd: "ansible-vault encrypt_string --name '{{ item }}' "
        _enc: "{{ lookup('pipe', vault_cmd ~  my_pswd[item]) }}"

给出

shell> cat sample.yml
# BEGIN my_password1
my_password1: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          30343161323861646333623332303663326438336462613165633766313130363961366633343764
          3335393837613638633565616366353139623063366131640a616233616534386663666263653432
          36376530653139666634323435313433346263643634303463643963343937316562326634313437
          6262613663313664630a343830636436376366656534366438613435366664656132643866353030
          3633
# END my_password1
# BEGIN my_password2
my_password2: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          36653034373863613531643535353361636565633463626465393065316561353661666564633762
          6139666336666433646633303664633261626135343865380a656464363430643563373264343234
          38303034653332626238326432333236333439383365623866656262343436386137353638663436
          3261363962373237300a646263396432646134313561366662326439303739303061303936353134
          6235
# END my_password2
# BEGIN my_password3
my_password3: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          31383764376166363733313065636264343863346334386230333739316337306535313866303164
          3465616663626565623438316364326532306538303134640a313564356135373931306236373833
          62383563386230633265396261363861393530653034613732333962643233316535646462656331
          6566383662323266310a343337303465613334336638316132636238343637646235646565653532
          6134
# END my_password3

当您重复任务时,变量的加密将会更新。

相关内容