【问题标题】:lineinfile ansible module skips a linelineinfile ansible 模块跳过一行
【发布时间】:2017-04-28 15:29:37
【问题描述】:

我需要知道清单中的主机名索引。我正在使用下面的代码创建一个变量文件,我可以在后续的剧本中使用它

- name: Debug me
  hosts: hosts
  tasks:
      - debug: msg="{{ inventory_hostname }}"
      - debug: msg="{{ play_hosts.index(inventory_hostname) }}"
      - local_action: 'lineinfile create=yes dest=/tmp/test.conf
                   line="host{{ play_hosts.index(inventory_hostname) }}=
                   {{ inventory_hostname }}"'

我有以下库存文件

[hosts]
my.host1.com
my.host2.com

现在当我运行它时,在 /tmp 下生成的 test.conf 有时会有两个这样的主机名

host1= my.host2.com
host0= my.host1.com

当我每次运行相同的剧本几次时,在运行前清空 test.conf。很多时候文件只有一个条目

host1= my.host2.com

host0= my.host1.com

为什么相同的 ansible playbook 表现不同?

【问题讨论】:

    标签: ansible


    【解决方案1】:

    我认为问题在于您针对不同的主机运行两个线程,并且使用 local_action 不是线程安全的。

    尝试使用serial关键字:

    - name: Debug me
      hosts: hosts
      serial: 1
      tasks:
          - debug: msg="{{ inventory_hostname }}"
          - debug: msg="{{ play_hosts.index(inventory_hostname) }}"
          - local_action: 'lineinfile create=yes dest=/tmp/test.conf
                       line="host{{ play_hosts.index(inventory_hostname) }}=
                       {{ inventory_hostname }}"'
    

    编辑:如果只是尝试在本地主机上的清单中的主机列表上进行操作,那么执行此操作的更好方法是避免在主机上执行操作并首先使用 local_action。

    - name: Debug me
      hosts: localhost
      tasks:
      - lineinfile:
          create: yes
          dest: /tmp/test.conf
          line: "host{{ groups['hosts'].index(item)}}={{ item }}"
        with_items: " {{ groups['hosts'] }}"
    

    这将为您带来您想要的结果。然后你可以添加另一个 play 来对主机本身进行操作。

    【讨论】:

    • 当我尝试使用串行时,我得到以下结果 host0= my.host2.com host0= my.host1.com 两次都是 host0
    • 更新了我的答案,以提供一种更好的方法来完成此任务,而无需使用 serial 或 local_action。
    • 感谢您,但这无济于事,因为我正在尝试遍历远程库存列表并将主机名写入文件中。我不能将主机作为 localhost,然后它不会循环通过远程清单列表。
    【解决方案2】:

    解决方案我试图通过非线程安全的 Local_action: lineinfile 将收集的数据写入本地文件来避免竞争条件的问题。将其拆分为同一文件中的 2 个不同的播放。

    例如:

    - name: gather_date
      hosts: all
      any_errors_fatal: false
      gather_facts: no
      tasks:
        - name: get_Aptus_device_count_list
          shell: gather_data.sh
          become: true
          register: Aptus_device_count_list
          changed_when: false
    
    - name: Log_gathered_date
      hosts: all
      any_errors_fatal: false
      gather_facts: no
      tasks:
        - name: log_gathered_info
          local_action:  
              module: lineinfile
              dest: /home/rms-mit/MyAnsible/record_Device_count_collection.out 
              line: "\n--- {{ inventory_hostname }} --- \n
                 {{ Aptus_device_count_list.stdout }} \n.\n---\n"
          changed_when: false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 2015-07-29
      相关资源
      最近更新 更多