MikiBelavista
MikiBelavista

Reputation: 2758

Why do I have Syntax Error while loading Ansible YAML?

My playbook.yml

---
- hosts: all
  var_files: 
   -vars.yml
  strategy : free

  tasks:
   - name: Add the Google signing key
     apt_key : url=https://packages.cloud.google.com/apt/doc/apt-key.gpg state=present

   - name: Add the k8s APT repo
     apt_repository: repo='deb http://apt.kubernetes.io/ kubernetes-xenial main' state=present

   - name: Install packages
     apt: name="{{ item }}" state=installed update_cache=true force=yes with_items: "{{ PACKAGES }}"

When I run

ansible-playbook -i hosts playbook.yml

Error occurs ,althouh I have slightly modified file. The offending line appears to be:

   - name: Install packages
     apt: name="{{ item }}" state=installed update_cache=true force=yes with_items: "{{ PACKAGES }}"
                                                                                  ^ 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 }}"

I am on Ubuntu,so apt syntax is not a problem for sure. Packages

cat vars.yml 
---
PACKAGES:
- vim
- htop
- tmux
- docker.io
- kubelet
- kubeadm
- kubectl
- kubernetes-cni

I am newbee to Ansible,how to fix this simple problem?

Upvotes: 1

Views: 542

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28854

with_items should be associated with a task and not a module (you associate it with apt instead of the entire task). Additionally, placing a key value pair at the end of a line of a key value pair is invalid YAML syntax. Check iteration documentation for more information.

You can fix the error like this:

- name: Install packages
  apt: name="{{ item }}" state=installed update_cache=true force=yes
  with_items: "{{ PACKAGES }}"

I would also recommend using modern Ansible formatting for tasks here:

- name: Install packages
  apt:
    name: "{{ item }}"
    state: installed
    update_cache: true
    force: yes
  with_items: "{{ PACKAGES }}"

Note also that in modern Ansible you may get a warning for using with_items with package installation tasks. It is now recommended to place the array of packages directly in the name parameter:

- name: Install packages
  apt:
    name: "{{ PACKAGES }}"
    state: installed
    update_cache: true
    force: yes

Upvotes: 3

Related Questions