1. ホーム
  2. Qt

ansibleのitemsとwith_itemsを理解する

2022-02-18 07:27:29

item はループ変数です。


    ################################## Variable Naming  
    Variable names can only consist of letters, numbers, and underscores and can only start with a letter.  
       
    ################################## facts  
    facts is information sent back from the remote target host that is communicating. This information is stored in the ansible variable. To get all the facts supported by a given remote host, use the following command  
    # ansible hostname -m setup This command obtains various information about the monitored host and saves this information to a variable.  
       
    ################################ Custom Variables  
    Variables can be defined in yaml using the vars keyword  
    vars:  
    var_name: value  
       
    ############################# Reference to a variable  
    {
{ var_name }}  
       
       
    ########################### Special Variable Iteration  
    The iteration mechanism can be used when there is a task that needs to be performed repeatedly. The format is to define the content to be iterated over as an item variable reference and specify the list of elements to be iterated over with the with_items statement.  
       
    ####################################### example  
    For example, adding 2 users to the Controlled side  
       
    The general approach for method 1  
    - name: add user testuser1  
    user: name=testuser1 state=present groups=wheel 
    - name: add user testuser2  
    user: name=testuser2 state=present groups=wheel 
       
    Way 2 uses the variable way  
    - name: add several users  
    vars:  
    user1: testuser1  
    user2: testuser2  
    user: name={
{ user1 }} state=present groups=wheel 
    user: name={
{ user2 }} state=present groups=wheel 
       
    Way 3 uses the iterative approach  
    - name: add several users  
    user: name={
{ item }} state=present groups=wheel 
    with_items:   
    - testuser1   
    - testuser2  
    In fact with_items can use elements that can also be hashes for example  
    - name: add several users  
    user: name={
{ item.name }} state=present groups={
{ item.groups }}  
    with_items:  
    - { name: 'testuser1', groups: 'wheel' }  
    - { name: 'testuser2', groups: 'root' } 














参考資料

http://os.51cto.com/art/201409/451927_all.htm