Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

How to add variables with command line in ansible?

i have to playbook for tower-cli command, which will create credentials with custom credentials type.

     - 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/g' test.pem )"}"
   no_log: false

This code is working prefectly, ssh file is aligned in the correct format.

As my code is quite messy, i added the sed command as variable, and passed that variable to cmd module like below.

---
- 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 file is not aligned like before input. To do this alignment i have used the sed command. What I am doing wrong here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot run the shell command using process substitution$(...) in vars. Although you can use lookup (2nd solution).

1st approach:

You can add a task to process the key using sed or by native approach and use it later by calling 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

2nd approach: If you really do not want to have an additional task for parsing keyy. This is using pipe/lookup. but this approach is fragile as compared to the one above.

---
- 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...