如何从YAML中的另一个动态变量分配变量

时间:2019-03-30 04:56:51

标签: ansible yaml

我需要从端口范围中找到一个开放的端口,然后将该端口分配给变量。我决定将wait_for与循环一起使用。但是我无法弄清楚如何“提取”准确的价值。示例:

- name: check open port
  wait_for:
    host: '0.0.0.0'
    port: '{{ item }}'
    delay: 0
    state: started
    timeout: 1
  ignore_errors: true      
  loop:
  - 22222
  - 33333
  - 44444
  register: temp_port_check

然后我如何查找/过滤打开的端口并将其分配给另一个变量,例如“ open_port”,并且如果所有端口都已关闭,请设置默认端口= 11111?

我在想类似的东西:

- name: set fact current open port
  set_fact:
    open_port: in pseudo 'find openned port in temp_port_check else = 11111'

temp_port_check的结果:

ok: [0.0.0.0] => {
    "msg": "Out: [{'_ansible_parsed': True, 'changed': False, '_ansible_no_log': False, 'item': 22222, '_ansible_item_result': True, u'elapsed': 1, u'failed': True, u'msg': u'Timeout when waiting for 0.0.0.0:22222', u'invocation': {u'module_args': {u'active_connection_states': [u'ESTABLISHED', u'FIN_WAIT1', u'FIN_WAIT2', u'SYN_RECV', u'SYN_SENT', u'TIME_WAIT'], u'host': u'0.0.0.0', u'connect_timeout': 5, u'delay': 0, u'search_regex': None, u'state': u'started', u'sleep': 1, u'timeout': 1, u'exclude_hosts': None, u'msg': None, u'path': None, u'port': 22222}}, '_ansible_item_label': 22222}, {'_ansible_parsed': True, 'changed': False, '_ansible_item_label': 33333, 'failed': False, '_ansible_item_result': True, u'elapsed': 0, 'item': 33333, u'state': u'started', u'invocation': {u'module_args': {u'active_connection_states': [u'ESTABLISHED', u'FIN_WAIT1', u'FIN_WAIT2', u'SYN_RECV', u'SYN_SENT', u'TIME_WAIT'], u'host': u'0.0.0.0', u'connect_timeout': 5, u'delay': 0, u'search_regex': None, u'state': u'started', u'sleep': 1, u'timeout': 1, u'exclude_hosts': None, u'msg': None, u'path': None, u'port': 33333}}, u'path': None, u'search_regex': None, u'port': 33333, '_ansible_ignore_errors': True, '_ansible_no_log': False}, {'_ansible_parsed': True, 'changed': False, '_ansible_no_log': False, 'item': 44444, '_ansible_item_result': True, u'elapsed': 1, u'failed': True, u'msg': u'Timeout when waiting for 0.0.0.0:44444', u'invocation': {u'module_args': {u'active_connection_states': [u'ESTABLISHED', u'FIN_WAIT1', u'FIN_WAIT2', u'SYN_RECV', u'SYN_SENT', u'TIME_WAIT'], u'host': u'0.0.0.0', u'connect_timeout': 5, u'delay': 0, u'search_regex': None, u'state': u'started', u'sleep': 1, u'timeout': 1, u'exclude_hosts': None, u'msg': None, u'path': None, u'port': 44444}}, '_ansible_item_label': 44444}]"
}

如何提取_ansible_item_label':33333值的状态为“失败”:False?

1 个答案:

答案 0 :(得分:0)

如果所有端口都关闭,请在下面播放

- name: List open_ports
  set_fact:
    open_ports: []
- set_fact:
    open_ports: "{{ open_ports + [ item.item ] }}"
  loop: "{{ temp_port_check.results }}"
  when: not item.failed
- name: Set default port
  set_fact:
    open_port: "{{ (open_ports|length == 0)|ternary('11111', open_ports.0) }}"
- debug:
    var: open_port

给予:

"open_port": "11111"

否则,第一个开放端口将分配给 open_port