ansible: переменная, не инициализированная повторно с использованием роли

#ansible #ansible-role

#ansible #ansible-роль

Вопрос:

у меня странное поведение, которое я не понимаю

Сборник воспроизведения «vars_roles.yml»:

 ---
- hosts: localhost
  gather_facts: no
  vars:
    msg_role3: "first_run"

  roles:
    - role: role3

- hosts: localhost
  gather_facts: no
  vars:
    msg_role3: "second_run"

  roles:
    - role: role3
  

Содержимое role3 :

cat roles/role3/defaults/main.yml

 ---
# defaults file for role3
add_value: false
msg_role3: "default"

tab_msg:
  - "Init value: {{ msg_role3 }}"
  

cat роли/role3/задачи/main.yml

 ---
# tasks file for role3

- name: Value
  debug:
    msg: "Variable is {{ msg_role3 }}"
- name: Content of Array
  debug:
    var: tab_msg

- name: Add "value" into Array
  set_fact:
    tab_msg: "{{ (tab_msg)   [item] }}"
  loop:
    - "value: {{ msg_role3 }}"
  when: add_value | bool

- name: Content of Array after add value
  debug:
    var: tab_msg
  

Итак, моя проблема возникла из set_fact со списком ‘tab_msg: «{{ (tab_msg) [item] }}»‘
если эта задача выполняется, список «tab_msg» сохраняет значения из первого запуска роли «role3»

Пример без set_fact :

 ansible-playbook vars_roles.yml -e add_value=false
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [localhost] ******************************************************************************************************************************************************

TASK [role3 : Value] **************************************************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.055)       0:00:00.055 *******
ok: [localhost] => {
    "msg": "Variable is first_run"
}

TASK [role3 : Content of Array] ***************************************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.053)       0:00:00.108 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: first_run"
    ]
}

TASK [role3 : Add "value" into Array] *********************************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.052)       0:00:00.161 *******
skipping: [localhost] => (item=value: first_run)

TASK [role3 : Content of Array after add value] ***********************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.052)       0:00:00.214 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: first_run"
    ]
}

PLAY [localhost] ******************************************************************************************************************************************************

TASK [role3 : Value] **************************************************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.058)       0:00:00.272 *******
ok: [localhost] => {
    "msg": "Variable is second_run"
}

TASK [role3 : Content of Array] ***************************************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.047)       0:00:00.319 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: second_run"
    ]
}

TASK [role3 : Add "value" into Array] *********************************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.048)       0:00:00.368 *******
skipping: [localhost] => (item=value: second_run)

TASK [role3 : Content of Array after add value] ***********************************************************************************************************************
Tuesday 27 October 2020  16:28:59  0100 (0:00:00.052)       0:00:00.420 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: second_run"
    ]
}

PLAY RECAP ************************************************************************************************************************************************************
localhost                  : ok=6    changed=0    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
  

Воспроизведен пример с set_fact :

 ansible-playbook vars_roles.yml -e add_value=true
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [localhost] ******************************************************************************************************************************************************

TASK [role3 : Value] **************************************************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.052)       0:00:00.052 *******
ok: [localhost] => {
    "msg": "Variable is first_run"
}

TASK [role3 : Content of Array] ***************************************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.052)       0:00:00.104 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: first_run"
    ]
}

TASK [role3 : Add "value" into Array] *********************************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.049)       0:00:00.154 *******
ok: [localhost] => (item=value: first_run)

TASK [role3 : Content of Array after add value] ***********************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.054)       0:00:00.208 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: first_run",
        "value: first_run"
    ]
}

PLAY [localhost] ******************************************************************************************************************************************************

TASK [role3 : Value] **************************************************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.053)       0:00:00.262 *******
ok: [localhost] => {
    "msg": "Variable is second_run"
}

TASK [role3 : Content of Array] ***************************************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.047)       0:00:00.309 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: first_run",
        "value: first_run"
    ]
}

TASK [role3 : Add "value" into Array] *********************************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.047)       0:00:00.357 *******
ok: [localhost] => (item=value: second_run)

TASK [role3 : Content of Array after add value] ***********************************************************************************************************************
Tuesday 27 October 2020  16:31:44  0100 (0:00:00.055)       0:00:00.412 *******
ok: [localhost] => {
    "tab_msg": [
        "Init value: first_run",
        "value: first_run",
        "value: second_run"
    ]
}

PLAY RECAP ************************************************************************************************************************************************************
localhost                  : ok=8    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
  

Есть идеи?

Спасибо

Ответ №1:

Результат, как вы видите, правильный. См. раздел «Понимание приоритета переменных«. Значение, присвоенное в set_fact, имеет более высокий приоритет (19.), Чем значения по умолчанию для роли (2.). В дополнение к этому, значение, присвоенное в set_fact, будет доступно для последующих воспроизведений во время выполнения ansible-playbook.

В приведенном ниже упрощенном примере set_fact (19.) имеет более высокий приоритет, чем play vars (12.)

 shell> cat pb.yml
- hosts: localhost
  vars:
    msg_role3: "first_run"
  tasks:
    - debug:
        var: msg_role3
    - set_fact:
        msg_role3: "Added value"
      when: add_value|default(false)|bool

- hosts: localhost
  vars:
    msg_role3: "second_run"
  tasks:
    - debug:
        var: msg_role3
  

дает (сокращенный)

 shell> ansible-playbook pb.yml

PLAY [localhost] ****

  msg_role3: first_run

PLAY [localhost] ****

  msg_role3: second_run
  
 shell> ansible-playbook pb.yml -e "add_value=true"

PLAY [localhost] ****

  msg_role3: first_run


PLAY [localhost] ****

  msg_role3: Added value
  

Решение вашей проблемы — удалить tab_msg из defaults/main.yml и поместить его в tasks/main.yml. Например

 shell> cat roles/role3/defaults/main.yml
add_value: false
msg_role3: "default"
  
 shell> cat roles/role3/tasks/main.yml
- name: Init tab_msg
  set_fact:
    tab_msg:
      - "Init value: {{ msg_role3 }}"
- name: Value
  ...
  

Комментарии:

1. Хорошо, я понимаю. Моя проблема в том, что переменная «tab_msg» известна в основном сборнике, мне нужно иметь что-то вроде частной переменной в роли.

2. При необходимости инициализируйте переменную в задаче. Я добавил пример к ответу.