我在 Ansible 中收到如下代码错误。请就此提供意见。
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each: JSON: Expecting value: line 1 column 1 (char 0) Syntax Error while loading YAML. did not find expected key The error appears to be in '/root/ansible_code/roles/sample_exercise/tasks/main.yml': line 10, column 6, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: oracle_home: "{{ oracle_home.stdout }}" oracle_sid: "{{ dbname }}" ^ 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 }}"
代码 -
#- hosts: localhost
- hosts: 192.168.56.10
- debug:
msg: "{{ oracle_home.stdout }}"
- set_fact:
oracle_home: "{{ oracle_home.stdout }}"
oracle_sid: "{{ dbname }}"
- name: List PDB of given CDB
shell:
cmd: |
$ORACLE_HOME/bin/sqlplus / as sysdba <<EOF
select instance_name, status from v$instance
EOF
environment:
ORACLE_HOME: "{{ oracle_home }}"
ORACLE_SID: "{{ oracle_sid }}"
register: pdb
- name: List PDB
debug:
msg: "{{ pdb.stdout_lines|replace('\t', '') }}"
答案1
我在 Ansible 中收到如下代码错误。请提供建议。
这只是由于缩进不正确而导致的语法错误。可以使用如下简单示例重现此错误
- hosts: localhost
become: false
gather_facts: false
tasks:
- set_fact:
oracle_home: 'get_assigned'
oracle_sid: 'will_cause_syntax_error'
输出结果为
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: No JSON object could be decoded
Syntax Error while loading YAML.
did not find expected key
The error appears to be in '/home/user/test/main.yml': line 9, column 8, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
oracle_home: 'get_assigned'
oracle_sid: 'will_cause_syntax_error'
^ here
正确的语法如下
- set_fact:
oracle_home: 'get_assigned'
oracle_sid: 'also_gets_assigned'
答案2
作为已经回答:您的错误很可能是剧本中的语法错误。在学习和使用 Ansible 时,有意义的空格和混乱的编码/格式很难融为一体。
在剧本执行期间,与其依靠 Ansible 错误消息来查找(语法)错误,不如使用类似ansible-lint
运行之前ansible-playbook
检查你的剧本和 yaml 文件是否存在语法错误和常见陷阱。