使用Ansible模块lineinfile添加,示例代码如下:
- name: Add entry to /etc/hosts file
lineinfile:
dest: /etc/hosts
line: "{{ host_ip }} {{ hostname }}"
state: present
regexp: '^{{ host_ip }}'
become: true
become_user: root
其中,lineinfile
是一种用于在文件中添加或修改行的Ansible模块,dest
指定文件路径,line
指定要添加的行内容(“{{ host_ip }} {{ hostname }}”),state
指定操作状态(present表示要添加行),regexp
则指定要查找的与新行相同的正则表达式(以host_ip
为开头的行)。最后,become
和become_user
指定以root身份执行该任务。
上述示例代码将添加“{{ host_ip }} {{ hostname }}”(例如:“192.168.1.100 myhost”)到文件"/etc/hosts"中,如果文件中已经存在以host_ip
为开头的行,则替换该行。