Using hyphen in ansible

2020-07-08 04:15发布

问题:

I am learning Ansible but I am getting confused when to use hyphen and when not to use hyphen in playbook. As I know, hyphen is used for list in Ansible.

For example,

--- # my first playbook
      - hosts: webservers  ( why did we use hyphen here it is not a list)
        tasks: 
          - name: installing httpd
            yum: name=httpd state=installed ( why we shouldn't use hyphen here).

From Ansible documentation, it is said that hyphen is for list, for example:

fruits:
  - apple
  - grapes
  - orange

So, I am confused when to use hyphens and when not to use.

回答1:

Hyphen - is used to specify list items, and colon : is used to specify dictionary items or key-value pair. I think a comparable example with another language (e.g. Python) will make this clear. Let's say you have a list my_list like this:

my_list = ['foo', 'bar']

In Ansible you will specify this list items with hyphen:

my_list:
  - foo
  - bar

Now let's say you have a key-value pair or dictionary like this:

my_dict = {
    'key_foo': 'value_foo', 
    'key_bar': 'value_bar'
}

In Ansible, you will use colon instead of hyphen for key-value pair or dictionary:

my_dict:
  key_foo: value_foo
  key_bar: value_bar

Inside a playbook you have a list of plays and inside each play you have a list of tasks. Since tasks is a list, each task item is started with a hyphen like this:

tasks:
  - task_1

  - task_2

Now each task itself is a dictionary or key value pair. Your example task contains two keys, name and yum. yum itself is another dictionary with keys name, state etc.

So to specify task list you use hyphen, but since every task is dictionary they contain colon.



回答2:

Any hyphen indicates a new item in a list, as is the case in "- hosts: webservers". Any item without a hypen belongs to its parent item that prefix with hypen. That's to say "yum: name=httpd state=installed" belongs to "- name" in your example.



回答3:

Is this equivalent python syntax if i convert above playbook?

[ hosts,
        tasks:[
                name,{ yum: { 
                                name:httpd, state:installed
                                }   
                        }   
                ]   
]

Please correct me if i am wrong.