Error the field hosts is required but was not set

7 votes and 7 comments so far on Reddit

EDIT: Ugh, I see what I did wrong… do you? I put a — in front of roles: which therefore was expecting another hosts definition. Removing the — caused everything to work. BRB reading: http://docs.ansible.com/ansible/YAMLSyntax.html

Tl;dr: I should read up on YAML Syntax

I’m still in the process of learning Ansible and I’ve gotten stuck somewhere and I can’t make any sense of it. I’ve tried googling, and I haven’t found anything like this…

I’m writing a playbook that will configure a new server after being deployed from my VPS host, so it requires that I ssh in as root via password. Since this playbook will be run ad-hoc, I don’t have a need for a host file, so I am specifying it in the command. At first, it seems to work but then fails with the error: ERROR! the field ‘hosts’ is required but was not set. The weirdest part is even if I create a host file with this server in it and call the group in the site.yml I still get the same error.

Any ideas?

site.yml:

---
- name: Configure new server
  hosts: all
  remote_user: root
  
- roles:
    - common

Command Output:

(tom):~/Documents/Ansible/vmdeploy $ ansible-playbook site.yml --ask-pass -i 104.233.126.209, -vvv
No config file found; using defaults
SSH password: 
2 plays in site.yml

PLAY [Configure new server] ****************************************************

TASK [setup] *******************************************************************
<104.233.126.209> ESTABLISH CONNECTION FOR USER: root on PORT 22 TO 104.233.126.209
<104.233.126.209> EXEC mkdir -p "$( echo $HOME/.ansible/tmp/ansible-tmp-1454358368.39-206618835657293 )" && echo "$( echo $HOME/.ansible/tmp/ansible-tmp-1454358368.39-206618835657293 )"
<104.233.126.209> PUT /var/folders/lm/ks77dycs5n7c7sk6jpy8v2980000gn/T/tmp_oMzRq TO /root/.ansible/tmp/ansible-tmp-1454358368.39-206618835657293/setup
<104.233.126.209> EXEC LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1454358368.39-206618835657293/setup; rm -rf "/root/.ansible/tmp/ansible-tmp-1454358368.39-206618835657293/" > /dev/null 2>&1
ok: [104.233.126.209]
ERROR! the field 'hosts' is required but was not set
  • 2

    0
    Votes

    2
    Posts

    0
    Views

    emmalee

    Looks like the piton interpreter doesn’t know where to find a studsite. It’s probably your django-appendix connected to the construction.
    Make sure that the structures correctly indicate the way to the root of the project.
    Add the sys.path to the catalogue where the studsite is with your app.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    D

    When calling method .submit() Validity verification is not performed. It is assumed that this is done by hand. So don’t forget to call method. .checkValidity() before dispatch:let $form = document.getElementById(‘form’),
    $submitBtn = document.getElementById(‘submit’);
    $submitBtn.addEventListener(‘click’, function() {
    if( $form.checkValidity() ) {
    $form.submit();
    } else {
    // ваша обработка ошибок
    }
    });
    Source: https://learn.javascript.ru/forms-submit#%D0%BC%D0%B5%D1%82%D0%BE%D0%B4-submit

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    inna

    One way to install Linux apps on Ubuntu is through Anbox. It’s very resource efficient, using your Ubuntu kernel to run Android apps without emulating the Android kernel or running Android in a VM. However, it’s still in alpha, so getting it set up takes a while and apps might crash or not work at all.
    Also, you’ll need to find the APK somewhere (e.g. APKMirror), as the Play store isn’t included.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    J

    {{ t | json_query(‘max_by(@, &a)’) }}»

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    B

    At the time of the crypt, the document has not yet been downloaded. First option.
    You need to analog the jquery method $(document).ready().
    For example, summon its method inside window.onload = function(){};
    Please note that this is the only way to put an event function once. If it’s not enough, you have to make your cross-sbrauser analog jquery bind.There’s a second option. Relocate the violin to the bottom of the document.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    R

    You have two mistakes: the number of fields doesn’t match, and a few teams on one.private void button4_Click(object sender, EventArgs e)
    {
    if (tbName.Text != «» && tbSurname.Text != «»)
    {
    SQLiteCommand CMD = DB.CreateCommand();
    CMD.CommandText = «insert into Personal(FIO) values(@Name);»;
    CMD.Parameters.Add(«@Name», System.Data.DbType.String).Value = tbName.Text.ToUpper();
    CMD.ExecuteNonQuery();
    SQLiteCommand CMD = DB.CreateCommand();
    CMD.CommandText = «insert into Personal(Age) values(@Age);»;
    CMD.Parameters.Add(«@Age», System.Data.DbType.String).Value = tbAge.Text.ToUpper();
    CMD.ExecuteNonQuery();

    }

    Call attention, team. insert into Personal(column1, column2) values(@value1) Not correct: how many parameters in the first brackets should be the same as in the second brackets.I’ve on my very simple path: I’ve just cleaned up one parameter, but you (as soon as the data start to be included in the table) have to either do two columns instead of the FIO column (Name and Surname) and make each field stand separate, or a box of lines (which is much worse, because it loses information about where the name is and where the name is. Believe me, the experience with physicals across Russia shows that a man does not always have one name or that there will be only two gaps in the FIS… IPs have to be asked manually because cars don’t always recognize this information correctly.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    R

    In the 1980s, green phosphorus monitors were used, and they often presented ‘ghosts’ on the screen. In addition to inspiring this visual hacking, it also inspired that matrix look.see more in: https://pt.wikipedia.org/wiki/Monitor_de_f%C3%B3sforo_verde

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    E

    If you go to Wikipedia, you can find an article. https://ru.wikipedia.org/wiki/%D0%90%D0%B1%D1%81%D1%82%D1%80%D0%B0%D0%BA%D1%86%D0%B8%D1%8F_%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85 where it is defined asAn abstraction in objective-oriented programming is the use of only the characteristics of the facility that are sufficiently accurate in the system. The main idea is to provide the object with a minimum set of fields and methods, with sufficient precision for the task to be addressed.The section of the references contains an article http://www.cyberguru.ru/programming/cpp/cpp-data-abstraction.html?showall=&start=0 where the concept is more detailed in the context of C+++ and defined asThe fundamental idea is to share the non-material details of the subprogramme and the characteristics essential for its correct use.While the division of the code between the headline files and implementation files may be necessary in the creation of data abstractions, this separation is not in itself a means of creating abstractions. This separation exists because for historical reasons, the C/C+++ uses a separate compilation with a text-processor, which, in the first stage, collects one long text of the unit of transmission from many text files.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    Z

    Depends on what system you want to write. I think a simple system (in the sense of core) can write one person. And if, from zero, the full-fledged general-purpose NEOs and the graphic interface, a few thousand developers, two to three years + a few billion dollars. In addition, LOs are different: general, real time, distributed, built. There’s going to be a specialty here, too.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    Bogopo

    The most universal, simple and reliable way is to make a second user with uid=0 and give him another password.
    In BSD systems, this method was originally described as a regular (the second was called toor; the original user had a shell csh and a toor sh).
    The call team will have to recruit not a «su» but a «su toor» with the right options.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    R

    Generally in order to do this, a perquisite is to root the device. There are actually dedicated apps on the play-store (Kali-Linux) (Backtrack is out of date)… that are an all in one process. Try a search and the application will guide you through the process. Be careful, you can end up bricking the device. I would recommend using an old one or ensuring backup data is on standby to reinstall via usb.

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    B

    You could establish attributes html:
    example @Html.EditorFor(model => model.Country.Name, new { htmlAttributes = new { @class = «form-control», required=»required» } })
    use the required
    I hope you help!

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    M

    Just take a simple test:LinkedList<String> list = new LinkedList<>();
    list.add(1, «cde»);
    This code launches a IndexOutOfBoundsException, and the reason is in https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html .The constructor without arguments https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html#LinkedList— (i.e. zero size):LinkedList<String> list = new LinkedList<>();
    System.out.println(list.size()); // 0
    And https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html#add-int-E- , throws the exception IndexOutOfBoundsException if the value of the index is less than zero or greater than the size of the list:IndexOutOfBoundsException — if the index is out of range (index < 0 || index > size())As the size of the list is zero, pass 1 to the method add throws the exception.In short, we can only use indices that are between zero and the size of the list:LinkedList<String> list = new LinkedList<>();
    list.add(«abc»);
    list.add(«def»);
    list.add(1,»xy»);
    System.out.println(list.size()); // 3
    System.out.println(list); // [abc, xy, def]
    list.add(3, «ultimo»); // índice é igual ao tamanho, é o mesmo que inserir no final
    System.out.println(list); // [abc, xy, def, ultimo]
    list.add(5,»abcde»); // IndexOutOfBoundsException

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    S

    I see several things:I don’t know if it’s a writing error in the question, but you have a line.Allow fromm All
    should be with a single ‘m’:Allow from all
    Or also, depending on your apache version, the configuration could be like this:<Directory «C:xampphtdocsmySymfonyProjectV2Symfonyweb»>
    AllowOverride All
    Require all granted
    </Directory>

  • 2

    0
    Votes

    2
    Posts

    0
    Views

    Marcee

    You wrote once. arrayAnd inside the body, who will write this word to announce other masses, Pushkin?$leftMenu = array (
    array (‘link’ => ‘Домой’, ‘href’ => ‘index.php’),
    array (‘link’ => ‘О нас’, ‘href’ => ‘about.php’),
    array (‘link’ => ‘Контакты’, ‘href’ => ‘contact.php’),
    array (‘link’ => ‘Таблица умножения’, ‘href’ => ‘table.php’),
    array (‘link’ => ‘Калькулятор’, ‘href’ => ‘calc.php’)
    );

ТИП ПРОБЛЕМЫ
  • Сообщение об ошибке
КОМПОНЕНТ НАЗВАНИЕ

playbook

ДОСТУПНАЯ ВЕРСИЯ
ansible 2.5.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.9 (default, Jun 29 2016, 13:08:31) [GCC 4.9.2]
КОНФИГУРАЦИЯ
ОС / СРЕДА

Запускается с: Debian GNU / Linux 8.10 (jessie)

РЕЗЮМЕ

хосты больше не принимают переменную от vars_prompt
Это нормально работало до версии 2.5.0.

ДЕЙСТВИЯ ПО ВОСПРОИЗВЕДЕНИЮ
---
- hosts: "{{ target }}"
  vars_prompt:
    - name: target
      prompt: "Enter target(s) (separate by ',')"
      private: no
      when: target == ""
ОЖИДАЕМЫЕ РЕЗУЛЬТАТЫ

Чтобы получить запрос на «цели» перед выполнением, если не указано с параметром -e «target = something»

ФАКТИЧЕСКИЕ РЕЗУЛЬТАТЫ
ansible-playbook 2.5.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible-playbook
  python version = 2.7.9 (default, Jun 29 2016, 13:08:31) [GCC 4.9.2]
Using /etc/ansible/ansible.cfg as config file
Parsed /etc/ansible/hosts inventory source with ini plugin

PLAYBOOK: upgrade-packages.yml ********************************************************************************************************************************************************************************
1 plays in playbooks/upgrade-packages.yml
ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'target' is undefined

The error appears to have been in '/root/playbooks/upgrade-packages.yml': line 2, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

---
- hosts: "{{ target }}"
  ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

Все 26 Комментарий

@zubfatal Пожалуйста, проверьте с # 38000 и посмотрите,

Хорошая работа @samdoran Я могу подтвердить, что проблема устранена :)

Эта фиксация решает проблему для меня. Пожалуйста, добавьте исправление в следующем выпуске.

Благодаря!

Да, пожалуйста, было бы здорово добавить это — спасибо!

Терминология Git, вероятно, неверна …. Но когда это исправление будет включено? 2.5.5. по-прежнему имеет ту же проблему (к счастью, исправление достаточно легко применить)

Исправление, которое я придумал, небезопасно, потому что оно не выполняет никакой проверки типа. После некоторого обсуждения с другими кажется, что мне нужно переписать post_validate что более сложно, и я не дошел до этого.

Итак, собираетесь ли вы снова открыть https://github.com/ansible/ansible/pull/38000 или создать новый номер? Просто пытаюсь следить за исправлением. Vars_Prompt чрезвычайно важен для нас (по крайней мере, пока мы не установим Tower).

@dbpiv Открою новый пиар с исправлением. На самом деле я закрыл это случайно, когда переименовал ветки.

Всем привет,

Это нормально, что это больше не работает с ansible 2.6.1?

Я пробую эту простую пьесу:

- name: "Test playbook"
- hosts: "{{ hosts }}"
  vars_prompt:
    - name: "hosts"
      prompt: "Which hosts would you like to setup?"
      private: no
  tasks:
    - name: Just a simple test
      service:
        name: ssh
        state: restarted

Но это приводит к ошибке:

ERROR! the field 'hosts' is required but was not set

@coom : Я думаю, ваша проблема заключается в дополнительном

- name: "Test playbook"
  hosts: "{{ hosts }}"

@abadger Пробовал использовать эту модифицированную книгу (как было предложено):

- name: "Test playbook"
  hosts: "{{ cible }}"
  vars_prompt:
    - name: "cible"
      prompt: "Which hosts would you like to setup?"
      private: no
      when: cible == ""
  tasks:
    - name: Just a simple test
      service:
        name: ssh
        state: restarted

Все равно не повезло:

ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'cible' is undefined

The error appears to have been in '/home/ansible/Test/GTR/ssh.yml': line 1, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: "Test playbook"
  ^ here

@coom. Правильно. Теперь у вас есть ошибка, о которой идет речь :-)

@abadger : Хорошо, спасибо :)

Я подтверждаю, что у меня такая же проблема с Ansible 2.6.1

---
- hosts:
    - vagrant:&core
    - tag_aws_cloudformation_stack_name_{{ core_stack | regex_replace('-' , '_') }}:&core
  strategy: "{{ extravars_ansible_strategy | default('linear') }}"
  vars_prompt:
  - name: "core_stack"
    prompt: "What Core AutoScalingGroup do you wish to provision?"
    default: "core-dev-stack-blue"
    private: no
  roles:
    - role: core
 [..]
ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'core_stack' is undefined

The error appears to have been in 'ansible/playbooks/core.yml': line 9, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- hosts:
  ^ here

Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.
(ansible-2.6.1) $ ansible-playbook --version
ansible-playbook 2.6.1
  config file = /home/mickael/git/devops/ansible/ansible.cfg
  configured module search path = [u'/home/mickael/git/devops/ansible/modules']
  ansible python module location = /home/mickael/ansible-2.6.1/local/lib/python2.7/site-packages/ansible
  executable location = /home/mickael/ansible-2.6.1/bin/ansible-playbook
  python version = 2.7.12 (default, Dec  4 2017, 14:50:18) [GCC 5.4.0 20160609]

Имею исправное исправление (плюс тесты!). Провел меня в длинной кроличьей норе, но это было поучительно. Буду признателен за тестирование / обратную связь с # 39304. Я хочу сделать это в следующих выпусках 2.5 и 2.6.

Не могли бы вы посоветовать, что нужно сделать, чтобы получить это исправление для ansible v2.6.2?

- hosts: "{{ hosts }}"
  vars_prompt:
    - name: "hosts"
      private: no

Я прокомментировал # 39304 напрямую …. Но для полноты я отвечу и здесь.

На данный момент я использовал обновленную версию более 70 раз с различными комбинациями —extra-vars и vars_prompts. Пока проблем не было.

Спасибо за патч @samdoran .

Пока люди ждут, когда # 39304 будет включен в выпуск, простое исправление для запуска playbook — использовать параметр --extra-vars :

ansible-playbook upgrade-packages.yml --extra-vars="target=host.example.com"

__Запись:__

1. target — это имя переменной, которая предоставляет хост для playbook, у вас может быть другое имя. Найдите в своей книге hosts: " {{ example }}" где example — имя вашей переменной.

2. host.example.com — это хост, на котором вы хотите, чтобы playbook работал.


@samdoran Могу ли я как-нибудь помочь добавить # 39304 в следующие выпуски 2.5 и 2.6?

Спасибо @dsofeir … Это было разработано как работа на раннем этапе, однако в нашей среде более 90% сценариев запускаются вручную. Vars_prompt просто предоставляет метод, который лучше подходит для наших людей, которые запускают playbooks по запросу.

Но я полностью согласен с вашим вопросом к @samdoran. Чем еще мы можем помочь?

Изображение ниже — это ошибка, которую я получаю. Это просто расстраивает. Кто-нибудь может мне помочь?

playbook.yml

---
- name: Hosted Services API
  hosts: api
  vars_prompt:
    name: "hosts"
    private: no
  vars:
    py_version: "2.7.10"

инвентарный файл

[all:vars]
ansible_python_interpreter = /usr/bin/python3

[api]
XXX.XXX.XXX.XXX

screen shot 2018-08-12 at 17 13 19

Думаю, я просто укажу версию Ansible, которая раньше работала у меня, вместо последней версии, которая называется ansible-2.6.2. Это подходит для меня.

@dbpiv @dsofeir Спасибо за проверку исправления. На прошлой неделе я был в отпуске. Я объединю # 39304 и перенесу обратно.

Исправление этой проблемы было перенесено в stable-2.5 и stable-2.6 и будет выпущено в Ansible 2.5.8 и 2.6.3.

Была ли эта страница полезной?

0 / 5 — 0 рейтинги

Понравилась статья? Поделить с друзьями:
  • Error the evaluation period already expired on this computer
  • Error the device cannot be loaded try setting the usb configuration to data transfer
  • Error the cpu core to bus ratio or vid configuration has failed что это
  • Error the circuit is not grounded simulation requires at least one ground
  • Error the changes could not be applied error code 1