Ansible随机UUID生成

Mud*_*aer 13 ansible

在我的Ansible脚本中,我希望动态生成UUID并在以后使用它们.

这是我的方法:

- shell: echo uuidgen
  with_sequence: count=5
  register: uuid_list


  - uri: 
      url: http://www.myapi.com
      method: POST
      body: "{{ item.item.stdout }}"
    with_items: uuid_list.result
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

fatal: [localhost] => One or more undefined variables: 'str object' has no attribute 'stdout'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

小智 15

在ansible 1.9中有一个新的过滤器:to_uuid,它给出一个字符串,它将返回一个特定于ansible域的UUID,你可以在这里找到用法https://docs.ansible.com/playbooks_filters.html#other-useful-filters

  • 使用相同的输入结果总是相同的,所以你需要像`{{ansible_date_time.iso8601_micro | to_uuid}}`得到一个真正的uuid. (8认同)
  • J0hnG4lt这种方法不会产生随机的uuid. (3认同)

Wil*_*ich 11

正如高兴兴所提到的to_uuid,可以使用足够大的数字和random过滤器来产生随机UUID.数字越大,随机性越大.例如:

{{ 99999999 | random | to_uuid }}
Run Code Online (Sandbox Code Playgroud)

要么

{{ 9999999999999999999999 | random | to_uuid }}
Run Code Online (Sandbox Code Playgroud)


adr*_*lzt 8

从包含大写/小写字母和数字的 20 个字符的字符串生成随机 UUID:

{{ lookup('password', '/dev/null chars=ascii_letters,digits') | to_uuid }}
Run Code Online (Sandbox Code Playgroud)

  • 已批准:这确实比基于*随机*过滤器的其他解决方案更好;您也可以只给出所需的长度(以及熵)作为参数;例如 `lookup( '密码', '/dev/null length=32' ) | to_uuid`。(`/dev/null` 因为我们不需要将生成的“密码”存储在文件中)更多[在文档中](https://docs.ansible.com/ansible/latest/plugins/lookup/password .html) (2认同)

ted*_*r42 5

这非常接近.我只需改变一些东西.我通过使用任务" debug: var=uuid_list"和迭代来解决这个问题.

- shell: uuidgen                # note 1
  with_sequence: count=5
  register: uuid_list
- uri:
    url: http://www.myapi.com
    method: GET
    body: "{{ item.stdout }}"    # note 2
    timeout: 1                   # note 3
  with_items: uuid_list.results  # note 4
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. echo导致uuidgen打印字符串.删除echo,保留uuidgen.
  2. item.item.stdout 需要 item.stdout
  3. 我使用了一个短暂的超时,所以我可以在没有休息端点的情况下测试它.这给出了失败错误消息,但很明显它是正确的.
  4. uuid_list.stdout 需要 uuid_list.results


小智 5

请注意,如果您使用 Willem 的解决方案,Jinja 和 Ansible 会缓存同一过滤器多次执行的结果,因此您每次都必须更改源编号

  api_key_1: "{{ 999999999999999999995 | random | to_uuid }}"
  api_key_2: "{{ 999999999999999999994 | random | to_uuid }}"
Run Code Online (Sandbox Code Playgroud)

对于需要普通 md5 而不是 to_uuid 的情况,hash('md5') 不采用整数。我发现将随机数转换为字符串的最方便方法是使用 to_uuid:

  api_key_3: "{{ 999999999999999999999 | random | to_uuid | hash('md5') }}"
  api_key_4: "{{ 999999999999999999998 | random | to_uuid | hash('md5') }}"
Run Code Online (Sandbox Code Playgroud)