如何在ansible中使用命令行添加变量?

问题描述

我必须为 Tower-cli 命令编写剧本,这将创建具有自定义凭据类型的凭据。

     - name: Create a valid SCM credential from a private_key file
   shell:
     cmd: tower-cli credential create --organization "Default" --name "DevOps User" --credential-type "csa-test2" --inputs "{'user':'devops','stg01_ssh_key':\"$( sed -z 's/\n/\\n/g' test.pem )\"}"
   no_log: false

此代码运行正常,ssh 文件以正确的格式对齐。

由于我的代码很乱,我将 sed 命令添加为变量,并将该变量传递给 cmd 模块,如下所示。

---
- name: Trigger an Atower API
  hosts: localhost
  connection: local
  vars:
     keyy: $( sed -z 's/^//' test.pem )

  tasks:
     - name: Create a valid SCM credential from a private_key file
       shell:
         cmd: tower-cli credential create --organization "Default" --name "DevOps User" --credential-type "csa-test2" --inputs "{'user':'devops','stg01_ssh_key':'{{ keyy }}'}"
       no_log: false

SSH 文件不像输入前那样对齐。为了进行这种对齐,我使用了 sed 命令。我在这里做错了什么?

解决方法

您不能在 vars 中使用进程替换$(...) 运行 shell 命令。虽然您可以使用 lookup(第二种解决方案)。

第一种方法:

您可以使用 sed 或通过本机方法添加一个任务来处理密钥,然后通过调用 keyy.stdout 使用它。

---
- name: Trigger an Atower API
  hosts: localhost
  connection: local


  tasks:
     - name:  Process the key file
       shell: sed -z 's/^//' test.pem
       register: keyy

     - name: Create a valid SCM credential from a private_key file
       shell:
         cmd: tower-cli credential create --organization "Default" --name "DevOps User" --credential-type "csa-test2" --inputs "{'user':'devops','stg01_ssh_key':'{{ keyy.stdout }}'}"
       no_log: false

第二种方法:如果您真的不想有额外的任务来解析 keyy。这是使用 pipe/lookup。但与上面的方法相比,这种方法是脆弱的。

---
- name: Trigger an Atower API
  hosts: localhost
  connection: local
  vars:
    keyy: >-
      {{ lookup('pipe','sed -z "s/^//g" test.pem') }}

  tasks:
  - name: Create a valid SCM credential from a private_key file
    shell:
    cmd: tower-cli credential create --organization "Default" --name "DevOps User" --credential-type "csa-test2" --inputs "{'user':'devops','stg01_ssh_key':'{{ keyy }}'}"
    no_log: false

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...