Error syntax error while loading yaml could not find expected

SUMMARY When parsing ini inventory files, warnings are presented about parse failures, however, all hosts and variables are imported properly. This appears to be related to a change starting with A...
SUMMARY

When parsing ini inventory files, warnings are presented about parse failures, however, all hosts and variables are imported properly. This appears to be related to a change starting with Ansible 2.4.2, which still exists on devel.

ISSUE TYPE
  • Bug Report
COMPONENT NAME

Inventory

ANSIBLE VERSION
ansible 2.7.0.dev0 (devel 8e26a58443) last updated 2018/07/10 15:11:44 (GMT -400)
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/rteague/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /home/rteague/git/clusters/aws-c2/ansible/lib/ansible
  executable location = /home/rteague/git/clusters/aws-c2/ansible/bin/ansible
  python version = 2.7.15 (default, May 15 2018, 15:37:31) [GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]

CONFIGURATION
OS / ENVIRONMENT
STEPS TO REPRODUCE

Two inventory files, ‘common’ and ‘inventory’:

# common
[all:vars]
ansible_ssh_user=ansible
ansible_become=yes
scp_if_ssh=True

[OSEv3:vars]
containerized=false
deployment_type=openshift-enterprise
openshift_deployment_type=openshift-enterprise
openshift_release=v3.7
openshift_image_tag=v3.7

# inventory
[all:vars]
filer_data_ip=10.10.10.11

[OSEv3:children]
masters
etcd
new_masters
lb
nodes
new_nodes 

[infralog]
foolo01s

[masters]
fooma01s
fooma02s
fooma03s

[new_masters]

[new_nodes]

[nodes]
foono01s openshift_node_labels="{'region':'primary','customer':'shared','logging-infra-fluentd':'true'}" 
foono02s openshift_node_labels="{'region':'primary','customer':'shared','logging-infra-fluentd':'true'}" 
foono03s openshift_node_labels="{'region':'primary','customer':'shared','logging-infra-fluentd':'true'}" 

fooma01s openshift_node_labels="{'region':'infra','openshift-infra':'apiserver'}"
fooma02s openshift_node_labels="{'region':'infra','openshift-infra':'apiserver'}"
fooma03s openshift_node_labels="{'region':'infra','openshift-infra':'apiserver'}"

[etcd]
fooet01s
fooet02s
fooet03s

[lb]
fooma01s state=master
fooma02s state=slave


[OSEv3:vars]
openshift_master_default_subdomain=openshift-apps-dev.svc.foo.net

Place the two files in a folder test, run ansible-inventory.

$ ansible-inventory -i test/ --list --yaml
EXPECTED RESULTS

Parse the files without warnings

ACTUAL RESULTS
$ ansible-inventory -i 1584122/test --list --yaml
 [WARNING]:  * Failed to parse /home/rteague/Downloads/1584122/test/common with yaml plugin: Syntax Error while loading YAML.   found
unexpected ':'  The error appears to have been in '/home/rteague/Downloads/1584122/test/common': line 1, column 5, but may be elsewhere in
the file depending on the exact syntax problem.  The offending line appears to be:   [all:vars]     ^ here

 [WARNING]:  * Failed to parse /home/rteague/Downloads/1584122/test/common with ini plugin: /home/rteague/Downloads/1584122/test/common:6:
Section [OSEv3:vars] not valid for undefined group: OSEv3

 [WARNING]: Unable to parse /home/rteague/Downloads/1584122/test/common as an inventory source

...

Related: https://bugzilla.redhat.com/show_bug.cgi?id=1584122
/cc @maxamillion

Вы хотите узнать, как использовать Ansible Lint?

Ansible – это инструмент автоматизации ИТ.

Ansible Lint – это инструмент командной строки, который анализирует код плейбука на предмет потенциальных ошибок.

Сегодня мы расскажем о том, как помогает процесс линтинга.

Содержание

  1. Что такое ansible-lint?
  2. Установка инструмента линтинга Ansible
  3. Как использовать ansible-lint?
  4. Как его настроить?
  5. Заключение

Что такое ansible-lint?

Прежде чем перейти к ansible-lint, давайте посмотрим на Ansible.

Ansible – это инструмент автоматизации ИТ с открытым исходным кодом.

Цель этого инструмента – конфигурирование систем, развертывание программного обеспечения и многое другое.

Обычно Ansible подключается к другим узлам через SSH и проталкивает в них модули Ansible. Ansible хранит свои конфигурации в файлах .yml.

Важным файлом YAML является плейбук Ansible.

Он определяет, как Ansible должен работать на узлах. Поэтому ошибки в YAML-файлах могут повлиять на работу Ansible.

Именно здесь мы используем инструмент командной строки, ansible-lint. Мы используем эту команду для линтинга плейбуков или файлов .yml в Ansible.

Процесс линтинга запускает программу, которая анализирует код и находит потенциальные ошибки в коде Ansible.

То есть она обнаруживает поведение и методы, которые нуждаются в улучшении.

Он может обнаружить синтаксические ошибки, неопределенные переменные и т.д.

Установка инструмента линтинга Ansible

Ansible-lint – это инструмент командной строки.

Он не входит в пакет Ansible, поэтому нам необходимо установить его. Мы можем установить его различными способами.

Чтобы установить его с помощью встроенного менеджера пакетов в Ubuntu, выполните команду,

apt install ansible-lint

Поскольку ansible-lint – это пакет Python, мы можем установить его с помощью команды,

pip install ansible-lint

Теперь давайте посмотрим, как его использовать!

Как использовать ansible-lint?

Чтобы получить полную информацию об использовании команды linting, мы используем,

ansible-lint --help

И вывод выглядит следующим образом:

Существует множество правил по умолчанию, используемых при линте плейбука.

Чтобы перечислить их, мы используем команду:

ansible-lint -L

Всего существует 18 правил по умолчанию.

Некоторые из них:

ANSIBLE0002: Trailing whitespace
There should not be any trailing whitespace
ANSIBLE0004: Git checkouts must contain explicit version
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0005: Mercurial checkouts must contain explicit revision
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0006: Using command rather than module
Executing a command when there is an Ansible module is generally a bad idea
ANSIBLE0007: Using command rather than an argument to e.g. file
Executing a command when there is are arguments to modules is generally a bad idea
ANSIBLE0008: Deprecated sudo
Instead of sudo/sudo_user, use become/become_user.
. . .

Например, если в плейбуке есть пробелы в конце, вывод линта будет выглядеть так:

ANSIBLE0002: Trailing whitespace

Выводится список нарушенных правил вместе с точным номером строки, где это произошло.

Аналогично, синтаксические ошибки в playbook выглядят следующим образом,

Syntax Error while loading YAML.
did not find expected '-' indicator

The error appears to be in '/etc/ansible/playbook.yml': line 14, column 6, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

name: Disable SELinux
^ here

Здесь отображается ошибочная строка вместе с точной ошибкой.

Самое главное, пользователь должен запустить команду linting в том же месте, где находится файл .yml.

Для сканирования всех файлов .yml в данном месте мы можем использовать команду,

ansible-lint *.yml

Как его настроить?

Далее рассмотрим возможность пользовательской настройки инструмента линтинга.

Мы можем настроить ansible-lint в соответствии с нашими требованиями.

Помимо правил по умолчанию, мы можем указать дополнительные правила в файле.

А флаг командной строки -c <путь к файлу> приведет к линтингу плейбука на основе пользовательской конфигурации.

Заключение

Итак, мы рассмотрели, как использовать инструмент командной строки ansible-lint

см. также:

  • 🔐 Создание самоподписанных сертификатов OpenSSL с помощью Ansible
  • 📜 Управление пользователями и группами в Linux с помощью Ansible
  • 🐧 Как временно остановить демон Auditd с Ansible
  • 🐧 Настройка кластера Elasticsearch на CentOS 8/7 | Ubuntu 20.04 / 18.04 с Ansible
  • 📜 Как создать зашифрованный пароль пользователя Linux для Ansible
  • 🔐 Как использовать Ansible Vault в плейбуках для защиты конфиденциальных данных
  • 💽 Шпаргалка Ansible Vault / Справочное руководство
  • Определите ключ ssh для каждого хоста, используя ansible_ssh_private_key_file
  • 🦊 Безопасность CI/CD – Как защитить свой пайплайн CI/CD

Are you looking at how to use Ansible Lint?

Ansible is an IT automation tool.

Ansible Lint is a command-line tool that analyzes playbook code for potential errors.

At Bobcares, we get many queries regarding Ansible, as a part of our Server Management Services.

Today, our Support Engineers will give an idea of how the linting process helps.

What is ansible-lint?

Before getting to ansible-lint, let’s have a look at Ansible.

Ansible is an open-source IT automation tool. The purpose of this tool is to configure systems, deploy software and many more.

Usually, Ansible connects to other nodes via SSH and pushes Ansible modules into them. Ansible holds its configurations in .yml files.

An important YAML file is Ansible playbook. It defines how the Ansible should work in the hosts. So errors in the YAML files can affect the working of Ansible.

This is where we make use of a command-line tool, ansible-lint. We use this command for linting playbooks or .yml files in Ansible.

A linting process runs a program that analyses code and finds potential errors in Ansible code. That is it detects the behaviors and practices that need improvement. It can detect syntax errors, undefined variables, etc.

Installing the linting tool in Ansible

Ansible-lint is a command-line tool. It does not come with the Ansible package, rather we need to install it. We can install it in various ways.

To install it using the built-in package manager in Ubuntu we use the command,

apt install ansible-lint

Since ansible-lint is a Python package we can install it using the command,

pip install ansible-lint

Now let’s see how our Support Engineers use the linting command in Ansible.

How to use ansible-lint?

To obtain complete information on using the linting command, we use,

ansible-lint --help

And the output appears as,

How to use ansible lint

There many default rules used while linting a playbook. To list them, we use the command,

ansible-lint -L

There are a total of 18 default rules. A few rules are,

ANSIBLE0002: Trailing whitespace
There should not be any trailing whitespace
ANSIBLE0004: Git checkouts must contain explicit version
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0005: Mercurial checkouts must contain explicit revision
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0006: Using command rather than module
Executing a command when there is an Ansible module is generally a bad idea
ANSIBLE0007: Using command rather than an argument to e.g. file
Executing a command when there is are arguments to modules is generally a bad idea
ANSIBLE0008: Deprecated sudo
Instead of sudo/sudo_user, use become/become_user.
. . .

For instance, if a playbook has trailing whitespace, the linting output shows up as,

How to use ansible lint

Here the output lists the violated rule along with the exact line number where it occurred.

Likewise, the syntax errors in playbook appear as,

Syntax Error while loading YAML.
did not find expected '-' indicator

The error appears to be in '/etc/ansible/playbook.yml': line 14, column 6, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

name: Disable SELinux
^ here

Here it displays the offending line along with exact error.

Most importantly, a user should run the linting command in the same location as that of the .yml file.

To scan all the .yml file in the location we can use the command,

ansible-lint *.yml

How to custom configure it?

Next, let’s see the possibility of custom configuring the linting tool.

We can custom configure ansible-lint for our requirement. Apart from the default rules, we can specify additional rules in a file.

And the command-line flag -c <file path> will lint the playbook based on the custom configuration.

[Need assistance in using Ansible lint? – We can help you.]

Conclusion

So far, we saw how to use the ansible-lint command-line tool. Today, our Support Engineers gave a complete guide on its installation, usage, and configuration.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Ansible – это инстру­мент авто­ма­ти­за­ции ИТ.

Ansible Lint – это инстру­мент команд­ной стро­ки, кото­рый ана­ли­зи­ру­ет код плей­бу­ка на пред­мет потен­ци­аль­ных ошибок.

Ansible – это инстру­мент авто­ма­ти­за­ции ИТ с откры­тым исход­ным кодом.

Цель это­го инстру­мен­та – кон­фи­гу­ри­ро­ва­ние систем, раз­вер­ты­ва­ние про­грамм­но­го обес­пе­че­ния и мно­гое другое.

Обыч­но Ansible под­клю­ча­ет­ся к дру­гим узлам через SSH и про­тал­ки­ва­ет в них моду­ли Ansible. Ansible хра­нит свои кон­фи­гу­ра­ции в фай­лах .yml.

Он опре­де­ля­ет, как Ansible дол­жен рабо­тать на узлах. Поэто­му ошиб­ки в YAML-фай­лах могут повли­ять на рабо­ту Ansible.

Имен­но здесь мы исполь­зу­ем инстру­мент команд­ной стро­ки, ansible-lint. Мы исполь­зу­ем эту коман­ду для лин­тин­га плей­бу­ков или фай­лов .yml в Ansible.

Про­цесс лин­тин­га запус­ка­ет про­грам­му, кото­рая ана­ли­зи­ру­ет код и нахо­дит потен­ци­аль­ные ошиб­ки в коде Ansible.

То есть она обна­ру­жи­ва­ет пове­де­ние и мето­ды, кото­рые нуж­да­ют­ся в улучшении.

Он может обна­ру­жить син­так­си­че­ские ошиб­ки, неопре­де­лен­ные пере­мен­ные и т.д.

Установка инструмента линтинга Ansible

Ansible-lint – это инстру­мент команд­ной строки.

Он не вхо­дит в пакет Ansible, поэто­му нам необ­хо­ди­мо уста­но­вить его. Мы можем уста­но­вить его раз­лич­ны­ми способами.

Что­бы уста­но­вить его с помо­щью встро­ен­но­го мене­дже­ра паке­тов в Ubuntu, выпол­ни­те команду,

apt install ansible-lint

Посколь­ку ansible-lint – это пакет Python, мы можем уста­но­вить его с помо­щью команды,

pip install ansible-lint

Теперь давай­те посмот­рим, как его использовать!

Как использовать ansible-lint?

Что­бы полу­чить пол­ную инфор­ма­цию об исполь­зо­ва­нии коман­ды linting, мы используем,

ansible-lint --help

И вывод выгля­дит сле­ду­ю­щим образом:

Суще­ству­ет мно­же­ство пра­вил по умол­ча­нию, исполь­зу­е­мых при лин­те плейбука.

Что­бы пере­чис­лить их, мы исполь­зу­ем команду:

ansible-lint -L

Все­го суще­ству­ет 18 пра­вил по умолчанию.

Неко­то­рые из них:

ANSIBLE0002: Trailing whitespace

There should not be any trailing whitespace

ANSIBLE0004: Git checkouts must contain explicit version

All version control checkouts must point to an explicit commit or tag, not just «latest»

ANSIBLE0005: Mercurial checkouts must contain explicit revision

All version control checkouts must point to an explicit commit or tag, not just «latest»

ANSIBLE0006: Using command rather than module

Executing a command when there is an Ansible module is generally a bad idea

ANSIBLE0007: Using command rather than an argument to e.g. file

Executing a command when there is are arguments to modules is generally a bad idea

ANSIBLE0008: Deprecated sudo

Instead of sudo/sudo_user, use become/become_user.

Напри­мер, если в плей­бу­ке есть про­бе­лы в кон­це, вывод лин­та будет выгля­деть так:

ANSIBLE0002: Trailing whitespace

Выво­дит­ся спи­сок нару­шен­ных пра­вил вме­сте с точ­ным номе­ром стро­ки, где это произошло.

Ана­ло­гич­но, син­так­си­че­ские ошиб­ки в playbook выгля­дят сле­ду­ю­щим образом,

Syntax Error while loading YAML.

did not find expected ‘-‘ indicator

The error appears to be in ‘/etc/ansible/playbook.yml’: line 14, column 6, but may

be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

name: Disable SELinux

^ here

Здесь отоб­ра­жа­ет­ся оши­боч­ная стро­ка вме­сте с точ­ной ошибкой.

Самое глав­ное, поль­зо­ва­тель дол­жен запу­стить коман­ду linting в том же месте, где нахо­дит­ся файл .yml.

Для ска­ни­ро­ва­ния всех фай­лов .yml в дан­ном месте мы можем исполь­зо­вать команду,

ansible-lint *.yml

Как его настроить?

Далее рас­смот­рим воз­мож­ность поль­зо­ва­тель­ской настрой­ки инстру­мен­та линтинга.

Мы можем настро­ить ansible-lint в соот­вет­ствии с наши­ми требованиями.

Поми­мо пра­вил по умол­ча­нию, мы можем ука­зать допол­ни­тель­ные пра­ви­ла в файле.

А флаг команд­ной стро­ки -c <путь к фай­лу> при­ве­дет к лин­тин­гу плей­бу­ка на осно­ве поль­зо­ва­тель­ской конфигурации.

Понравилась статья? Поделить с друзьями:
  • Error syntax error while loading yaml ansible
  • Error syntax error unrecognized expression nth child
  • Error syntax error operator expected prolog
  • Error syntax error at or near raise
  • Error syntax error at or near psql