在我的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
但是我收到以下错误:
fatal: [localhost] => One or more undefined variables: 'str object' has no attribute 'stdout'
我该如何解决这个问题?
小智 15
在ansible 1.9中有一个新的过滤器:to_uuid,它给出一个字符串,它将返回一个特定于ansible域的UUID,你可以在这里找到用法https://docs.ansible.com/playbooks_filters.html#other-useful-filters
Wil*_*ich 11
正如高兴兴所提到的to_uuid,可以使用足够大的数字和random过滤器来产生随机UUID.数字越大,随机性越大.例如:
{{ 99999999 | random | to_uuid }}
要么
{{ 9999999999999999999999 | random | to_uuid }}
从包含大写/小写字母和数字的 20 个字符的字符串生成随机 UUID:
{{ lookup('password', '/dev/null chars=ascii_letters,digits') | to_uuid }}
这非常接近.我只需改变一些东西.我通过使用任务" 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
笔记:
echo导致uuidgen打印字符串.删除echo,保留uuidgen.item.item.stdout 需要 item.stdoutuuid_list.stdout 需要 uuid_list.results小智 5
请注意,如果您使用 Willem 的解决方案,Jinja 和 Ansible 会缓存同一过滤器多次执行的结果,因此您每次都必须更改源编号
  api_key_1: "{{ 999999999999999999995 | random | to_uuid }}"
  api_key_2: "{{ 999999999999999999994 | random | to_uuid }}"
对于需要普通 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') }}"
| 归档时间: | 
 | 
| 查看次数: | 22903 次 | 
| 最近记录: |