ansible - 使用 ansible 插入 etc 主机文件

标签 ansible

我想使用 Ansible 以某种方式将以下条目插入到 /etc/hosts 文件中。

10.33.5.44 ip-10-33-5-44

这里的模式是 ip 应该有一个对应于 IP 的别名,前缀为 ip- 并且点 . 将被替换为破折号 -

但要获得此 IP,我只能考虑对 DNS 名称执行主机命令,例如

host euwest2-test-box.company.com
> euwest2-test-box.company.com has address 10.33.5.44

任何人都可以建议如何让它工作吗?可能吗?

最佳答案

您可以使用 dig查找以实现此目的。然后在主机文件中添加 lineinefile 行.

请注意模块dig需要Python库dnspython才能运行。因此,您可能还想将它与 Ansible 一起安装。

因此,根据剧本:

- hosts: all
  gather_facts: no
  
  tasks:
    - package:
        name: py-dnspython
        state: present
    - lineinfile:
        path: /etc/hosts
        line: "{{ item }} ip-{{ item | replace('.', '-') }}"
      loop: "{{ lookup('dig', 'stackoverflow.com.').split(',') }}"

这给出了回顾:

PLAY [all] *********************************************************************************************

TASK [package] *****************************************************************************************
changed: [localhost]

TASK [lineinfile] **************************************************************************************
changed: [localhost] => (item=151.101.1.69)
changed: [localhost] => (item=151.101.65.69)
changed: [localhost] => (item=151.101.129.69)
changed: [localhost] => (item=151.101.193.69)

PLAY RECAP *********************************************************************************************
localhost                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

并相应地填充主机文件:

127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3  21eef8264e0c
151.101.1.69 ip-151-101-1-69
151.101.65.69 ip-151-101-65-69
151.101.129.69 ip-151-101-129-69
151.101.193.69 ip-151-101-193-69

关于ansible - 使用 ansible 插入 etc 主机文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62870703/

相关文章:

amazon-ec2 - github repo 中缺少 Ansible 动态库存

Ansible 回调插件 : how to get play attribute values with variables expanded?

ansible - 如何禁用收集未包含在给定标签内的子播放的事实

java - apt_repository 模块失败

ansible - 在 playbook 中运行任务之前,如何设置确认提示?

loops - 如何在ansible循环中跳过空值

docker - 来自 OSX 的 Ansible Docker 模块

ansible - 使用 "when"在 ansible 中的单个任务上检查多个条件

Ansible 从结果中检索多个数组值

ssl - Ansible,如何信任证书?