Error yaml scanner scannererror mapping values are not allowed here in docker compose yml

AWX role fails with this error: Configuration error - yaml.scanner.ScannerError: mapping values are not allowed here\n in \"/tmp/awxcompose/docker-compose.yml Playbook: --- - name: Install ...

@agardnerIT

AWX role fails with this error:

Configuration error - yaml.scanner.ScannerError: mapping values are not allowed here\n  in \"/tmp/awxcompose/docker-compose.yml

Playbook:

---
- name: Install AWX
  hosts: awx
  become: yes

  vars:
    ansible_distribution_major_version: 6

  pre_tasks:

  - name: Install Python Pip
    package:
      name: python-pip
      state: present

  - name: Install Docker
    command: pip install docker

  - name: Install Docker Compose
    command: pip install docker-compose

  roles:

  - role: geerlingguy.repo-epel
  - role: geerlingguy.git
  - role: geerlingguy.ansible
  - role: geerlingguy.nodejs
  - role: geerlingguy.awx

@theMattCode

I got this, too. It seems that some lines are wrongly indented. Thx to significant whitespaces in YAML this leads to an error while tokenizing.
The errors are in line 10, 11, 20, 32, 33 and 40.

version: '2'
services:

  web:
    image: ansible/awx_web:4.0.0
    container_name: awx_web
    depends_on:
      - rabbitmq
      - memcached
            - postgres
          ports:
      - "80:8052"
    hostname: awxweb
    user: root
    restart: unless-stopped
    volumes:
      - "/var/awx/compose/SECRET_KEY:/etc/tower/SECRET_KEY"
      - "/var/awx/compose/environment.sh:/etc/tower/conf.d/environment.sh"
      - "/var/awx/compose/credentials.py:/etc/tower/conf.d/credentials.py"
                    environment:
      http_proxy:
      https_proxy:
      no_proxy:

  task:
    image: ansible/awx_task:4.0.0
    container_name: awx_task
    depends_on:
      - rabbitmq
      - memcached
      - web
            - postgres
          hostname: awx
    user: root
    restart: unless-stopped
    volumes:
      - "/var/awx/compose/SECRET_KEY:/etc/tower/SECRET_KEY"
      - "/var/awx/compose/environment.sh:/etc/tower/conf.d/environment.sh"
      - "/var/awx/compose/credentials.py:/etc/tower/conf.d/credentials.py"
                    environment:
      http_proxy:
      https_proxy:
      no_proxy:

  rabbitmq:
    image: ansible/awx_rabbitmq:3.7.4
    container_name: awx_rabbitmq
    restart: unless-stopped
    environment:
      RABBITMQ_DEFAULT_VHOST: "awx"
      RABBITMQ_DEFAULT_USER: "<REMOVED>"
      RABBITMQ_DEFAULT_PASS: "<REMOVED>"
      RABBITMQ_ERLANG_COOKIE: cookiemonster

  memcached:
    image: memcached:alpine
    container_name: awx_memcached
    restart: unless-stopped

    postgres:
    image: postgres:9.6
    container_name: awx_postgres
    restart: unless-stopped
    volumes:
      - /var/awx/postgres:/var/lib/postgresql/data:Z
    environment:
      POSTGRES_USER: <REMOVED>
      POSTGRES_PASSWORD: <REMOVED>
      POSTGRES_DB: awx
      PGDATA: /var/lib/postgresql/data/pgdata

@ikiraschielke

As - postgres is the value of the key depends_on it should be on the same level as - memcached. Thus the intendation of your next key ports is wrong too. Again, it should be on the same level as depends_on. The same applies for -postgres, hostname: awx and environment: .

@stale

This issue has been marked ‘stale’ due to lack of recent activity. If there is no further activity, the issue will be closed in another 30 days. Thank you for your contribution!

Please read this blog post to see the reasons why I mark issues as stale.

@stale

This issue has been closed due to inactivity. If you feel this is in error, please reopen the issue or file a new issue with the relevant details.

@Kashif1Naqvi

ERROR: yaml.scanner.ScannerError: mapping values are not allowed here
in «./docker-compose.yml», line 4, column 9
Show me this error I create space between version: ‘3’ it’s first mistake

my code look like this

version: "3"


services:
  app:
    build:
      context: .
    ports:
      - "8000:8000"
    volumes:
      - ./app:/app
    command: >
      sh -c "python manage.py runserver 0.0.0.0:8000"

when i write
docker-compose build
then show me one error more if any one show same read more my comment

ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.

Then I fix this by adding just sudo then work fine
sudo docker-compose build

make sure you using

docker pull jenkins/jenkins

only if you are using

docker pull Jenkins

then may face more issues

While installing Jenkins with docker you might face below errors, and these are the errors I have faced.

yaml.scanner.ScannerError:
yaml.scanner.ScannerError: while scanning for the next token found character ‘ ‘ that cannot start any token.

You are using the tabs inside the docker-compse.yml file; remove the tabs and use spaces instead

mapping values are not allowed here:
ERROR: yaml.scanner.ScannerError: mapping values are not allowed here in «./docker-compose.yml», line 6, column 10

You might have used double quotes for a value that not supposed to have double-quotes. Also, you might have provided value to a place where no value is required.

Version in «./docker-compose.yml» is invalid.

Version in «./docker-compose.yml» is invalid. You might be seeing this error because you’re using the wrong Compose file version. Either specify a supported version (e.g «2.2» or «3.3») and place your service definitions under the `services` key, or omit the `version` key and place your service definitions at the root of the file to use version 1.
the version you are using in the docker-compose.yml is not compatible with docker-compose.

jenkins say it is offline when I installed using docker:
WARNING: Upgrading Jenkins. Failed to update the default Update Site 'default'. Plugin upgrades may fail.
java.net.UnknownHostException: updates.jenkins-ci.org
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)

offline-jenkins-docker-vm

Firewall creating the issue, so execute the below commands, I am using centOS 8; please use commands according to your OS.

#allow traffic on port 80/443 on centos firewall using this command:

firewall-cmd --zone=public --add-masquerade --permanent
firewall-cmd --zone=public --add-port=80/tcp
firewall-cmd --zone=public --add-port=443/tcp
firewall-cmd --reload

#then reboot the OS.

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Ok, I wasted around 3 hours to debug a similar issue.

If you guys ever get the below error

ERROR: yaml.scanner.ScannerError: mapping values are not allowed here
in ".docker-compose.yml", line 2, column 9

It’s because a space is needed between

version:'3' <— this is wrong

version: '3' <— this is correct.

Also, if you are using eclipse, do yourself a favor and install the YEdit YAML editor plugin

And I forgot : after version

version '2'

Literally found the solution seconds later. You have to remove the «discovery-microservice» after «build»:

version: '2'
services:
  discovery-microservice:
    build:
      context: ./discovery-microservice/target/docker
      dockerfile: Dockerfile
    ports:
     - "8761:8761"

Also you can use «./» in context for relative paths. :)

What is wrong is that here:

    build: discovery-microservice

you start a mapping which has a key build indented by four spaces. The value for that key is a scalar that starts with discovery-microservice and possible continues to the next line, depending on whether that has a key: value pair at the same indentation level or not

What is not allowed inside such a multiline scalar is that you have an unquoted : and have that at a different indentation level. Which is exactly what you do have.

The parser seeing context indented at a different level than build assumes you are writing a scalar string discovery-microservice context which cannot be followed on the same line (as context) by a colon.

Apart from removing discovery-microservice after build as you did in your answer, what would also make this valid YAML (but with a different meaning, probably non-sense for docker compose) are:

services:
  discovery-microservice:
    build: "discovery-microservice
      context: /discovery-microservice/target/docker"

and

services:
  discovery-microservice:
    build: discovery-microservice
    context: /discovery-microservice/target/docker"

For docker-compose version 2 files, the build key expects a mapping (and not a scalar as in the «solutions» above), making your answer the correct way to solve this.

compose.yml файл, который выглядит так:

version: '2'
services:
  discovery-microservice:
    build: discovery-microservice
      context: /discovery-microservice/target/docker
      dockerfile: Dockerfile
  ports:
   - "8761:8761"

Пока я его выполняю, я получаю следующую ошибку:

yaml.scanner.ScannerError: mapping values are not allowed here
in "C:...docker-compose.yml", line 5, column 14

Насколько я вижу, с форматом все в порядке, например отсутствуют пробелы. Моя общая цель — указать файл docker-compose для режима разработки, указав его на целевые каталоги из разных модулей.
Что я здесь делаю не так?

16 ответов

Лучший ответ

Буквально через секунды нашел решение. Вы должны удалить «микросервис обнаружения» после «сборки»:

version: '2'
services:
  discovery-microservice:
    build:
      context: ./discovery-microservice/target/docker
      dockerfile: Dockerfile
    ports:
     - "8761:8761"

Также вы можете использовать «./» в контексте для относительных путей. :)


24

Skeffington
22 Авг 2016 в 10:53

Хорошо, я потратил около 3 часов на отладку аналогичной проблемы.

Если вы, ребята, когда-нибудь получите ошибку ниже

ERROR: yaml.scanner.ScannerError: mapping values are not allowed here
in ".docker-compose.yml", line 2, column 9

Это потому, что вам нужно пространство между

Версия: ‘3’ <- это неправильно

Версия: ‘3’ <- это правильно.

Кроме того, если вы используете eclipse, сделайте себе одолжение и установите плагин редактора YEdit YAML.


111

virtuvious
15 Авг 2017 в 00:54

Приношу свой ответ, потому что, хотя я получил такое же сообщение об ошибке, мое решение было другим.

Исходный файл docker-compose.yml

volumes: mongo:

Попробовав все идеи в этом потоке, я просто пошел в док-станции для создания докеров и понял, что тома должны быть структурированы следующим образом:

volumes:
  mongo:

Это все для всех, кто сталкивается с этим.


2

thatgibbyguy
28 Апр 2019 в 14:34

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

Моя ошибка была

ОШИБКА: yaml.scanner.ScannerError: значения сопоставления не разрешены здесь, в «./docker-compose.yml», строка 6, столбец 19

Неправильно:

version : '3'
services:
  test:
    build:
      context: ./test
        dockerfile: Dockerfile.test
    image: kpod/test:2020

Правильно:

version : '3'
services:
  test:
    build:
      context: ./test
      dockerfile: Dockerfile.test
    image: kpod/test:2020


2

Kamalikap
12 Май 2020 в 07:35

Привет, дальнейшее обновление данного ответа …. Это не конкретно о версии: строка ‘2.0’ Заявление

ОШИБКА: yaml.scanner.ScannerError: значения сопоставления здесь недопустимы

Означает, что есть какая-то ошибка форматирования.

Я получил это, потому что мне не хватало вкладки в моем файле docker-compose

version: '3.0'
services:
  mysql:
  image: ...

Вместо того

version: '3.0'
services:
  mysql:
    image: ...

Обратите внимание на отсутствие вкладки с отступом в строке изображения.


1

0x1gene
30 Сен 2018 в 01:49

Итак, есть еще одна причина! Когда вы пытаетесь установить r = Redash с помощью setup.sh из Github, скрипт автоматически получает последнюю версию Redash и помещает ее в docker-compose.yml. В базовом файле yml нет одинарных кавычек (‘) вокруг имени версии! В результате вы получите сообщение об ошибке:

ОШИБКА: yaml.scanner.ScannerError: значения сопоставления не разрешены здесь, в «./docker-compose.yml», строка 3, столбец 23. Вы просто добавляете одинарную кавычку вокруг версии Redash:

version: "2"
x-redash-service: &redash-service
  image: 'redash/redash:8.0.0.b32245'


0

mohammad hoseyny
19 Мар 2020 в 21:14

Используя расширение vs code yaml RedHat, я заметил, что отступил на один отступ:

Неправильно:

version: '3'

services:

  web:
    image: nginx
     ports:
    - 9090:80

  database:
    image: redis

Правильно:

version: '3'

services:

  web:
    image: nginx
    ports:
    - 9090:80

  database:
    image: redis


0

Jack BeNimble
4 Апр 2020 в 05:29

1) Ставьте пробел после каждого двоеточия всякий раз, когда вы выполняете сопоставление после определения ключа.

2) В файле YAML используется отступ 2 (два пробела или табуляции). -> Это означает, что после каждой строки вам нужно использовать две табуляции, когда вы пишете предложение в следующей строке. Я надеюсь, что теперь это упростит запись любого файла YAML.


0

Arbaaz khan
19 Мар 2020 в 20:44

Я обнаружил, что отсутствие одного ":" было достаточно, чтобы вызвать указанную выше ошибку


0

Feras
25 Окт 2020 в 03:55

Другой возможный виновник — случайные вкладки в конце файла, о которых я сегодня узнал.


0

Wesley A. Pettyjohn
13 Окт 2018 в 21:15

Неправильно вот что:

    build: discovery-microservice

Вы запускаете сопоставление с ключом build с отступом в четыре пробела. Значение для этого ключа представляет собой скаляр, который начинается с discovery-microservice и, возможно, продолжается до следующей строки, в зависимости от того, есть ли у него пара key: value на том же уровне отступа или нет.

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

Синтаксический анализатор, видящий context с отступом на другом уровне, чем build, предполагает, что вы пишете скалярную строку discovery-microservice context, за которой в той же строке (как context) не может следовать двоеточие. .

Помимо удаления discovery-microservice после сборки, как вы это сделали в своем ответе, что также сделало бы этот действительный YAML (но с другим значением, вероятно, бессмысленным для docker compose):

services:
  discovery-microservice:
    build: "discovery-microservice
      context: /discovery-microservice/target/docker"

А также

services:
  discovery-microservice:
    build: discovery-microservice
    context: /discovery-microservice/target/docker"

Для файлов docker-compose версии 2 ключ build ожидает сопоставления (а не скаляра, как в «решениях» выше), что делает ваш ответ правильным способом решения этой проблемы.


6

Anthon
22 Авг 2016 в 11:52

И я забыл : после version

version '2'


19

vladkras
28 Апр 2017 в 07:53

проверьте наличие пробела между

Порты:

— _space_ «8080: 8080»


0

Utk
20 Май 2020 в 08:28

Если вы используете vs code, сделайте себе одолжение и установите расширение YAML от RedHat.


1

MajidJafari
10 Янв 2020 в 05:45

Проверьте свои пробелы , проверив ввод YAML.

Я потратил час, чтобы узнать.


0

Bhargav Rao
5 Мар 2020 в 19:10

Я хотел, чтобы том был сопоставлен с определенным путем на внешнем (главном) сервере. Я попытался поместить это под запись верхнего уровня volumes в docker-compose.yml. Посмотрев на документацию файла docker-compose, я понял, что этот тип тома туда не подходит. Вместо этого он идет только под записью volumes в определении контейнера. Например.:

version: "3.7"
services:
  web:
    image: my_custom_web_image
    build: ./app
    volumes:
      - ./app/subdir:/usr/src/app/subdir


0

Stephen G Tuggy
28 Июн 2019 в 17:51

Понравилась статья? Поделить с друзьями:
  • Error xml parser perl module is required for intltool
  • Error xhr request timed out
  • Error xhr request aborted by browser
  • Error xgen searched path includes
  • Error x3000 unrecognized identifier