使用Ansible Tower REST API创建凭证

时间:2018-11-15 13:28:06

标签: rest api ansible ansible-tower

在我的Ansible Tower中,我有一个名为Token的自定义凭证,在其中存储了令牌,因此不必使用该凭证就可以登录,并且可以在各种作业中使用该凭证。

以下是必填字段-

  

名称:

     

凭据类型:(我们选择此自定义凭据类型)

     

API令牌值:(在其中输入令牌并也表示为   一个额外的变量my_token)

下面是我用来做有需要的yml文件-

—-

   Required info

   tasks:

      - name: Create credential

         uri:

             url: “https://ans........../api/v1/credentials/“

             method: “POST”

             kind: SecureCloud

             name: Token

             body:

                  extra_vars:

                      my_token: “{ key }”

             body_format: json

我对如何在上述剧本中输入字段值“名称”和“凭据类型”感到困惑。这样做时我还需要其他字段吗? uri模块中的网址也正确吗?

1 个答案:

答案 0 :(得分:0)

有两种创建自定义证书的方式(我更喜欢第二种):

第一种选择:您的方法-URI模块

- name: Create Custom Credential
  uri:
    url: "https://endpoint/api/v2/credentials/"
    method: POST
    user: admin
    password: password
    headers:
      Content-Type: "application/json"
    body: '{"name":"myfirsttoken","description":"","organization":34,"credential_type":34,"inputs":{"token":"MyToken"}}'
    force_basic_auth: true
    validate_certs: false
    status_code: 200, 201
  no_log: false

但是,请小心,因为这不是幂等的,您应该首先使用method: GET进行GET凭据,注册结果并在register.json.results变量中找到凭据。

第二个选择:我的首选方法-tower-cli

您可以使用以下方法进行完全相同,更轻松和幂等的操作:

- name: Add Custom Credential
  command: tower-cli credential create --name="{{ item }}" --credential-type "{{ credential_type }}" --inputs "{'token':'123456'}" -h endpoint -u admin -p password --organization Default
  no_log: true
  with_items:
    - MyCustomToken

您将得到类似的东西:

== ============= =============== 
id name          credential_type 
== ============= =============== 
46 MyCustomToken              34
== ============= =============== 

很棒的东西是您可以完全自动化令牌,甚至可以使用以下命令自动生成令牌:

token: "{{ lookup('password', '/dev/null length=20 chars=ascii_letters,digits') }}"

然后:

---
- name: Create Custom Credential Token
  hosts: localhost
  connection: local
  gather_facts: false

  vars:

    token: "{{ lookup('password', '/dev/null length=20 chars=ascii_letters,digits') }}"
    credential_type: MyCustom

  tasks:

    - name: Create Credential Type
      tower_credential_type:
        name: "{{ credential_type }}"
        description: Custom Credentials type
        kind: cloud
        inputs: {"fields":[{"secret":true,"type":"string","id":"token","label":"token"}],"required":["token"]}
        state: present
        tower_verify_ssl: false
        tower_host: endpoint
        tower_username: admin
        tower_password: password

    - name: Add Custom Credential
      command: tower-cli credential create --name="{{ item }}" --credential-type "{{ credential_type }}" --inputs "{'token':'{{ token }}'}" -h endpoint -u admin -p password --organization Default
      no_log: true
      with_items:
        - MyCustomToken