【问题标题】:Use ansible to insert into etc hosts file使用 ansible 插入 etc hosts 文件
【发布时间】:2020-07-13 06:58:21
【问题描述】:

我想使用 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

谁能建议如何让它发挥作用?有可能吗?

【问题讨论】:

  • 所以你只想在你的主机中创建一个别名,前缀为ip- ?
  • 是的,以 ip- 为前缀,也将点替换为“-”

标签: ansible


【解决方案1】:

您可以使用dig 查找来实现此目的。然后在 hosts 文件中添加带有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

【讨论】:

  • 好东西,但是我确实收到了权限被拒绝错误。我尝试使用become: true,但这也不起作用。有任何想法吗? - 见:justpaste.it/6qxot
  • 如果您还没有成为 root 用户,那么您需要在第一个打包任务中成为 root 用户
  • 也许您将更高级别的become_user 设置为另一个用户?如果是这样,您需要在package 任务中同时添加become: truebecome_user: root
  • 对,补充说。另外......有没有办法向它附加命令。我想在 conda 环境中运行它,因为我有 conda 正在运行。当我安装 dnspython 然后运行您的解决方案时......它抱怨没有名为 dnspython 的包。
  • 我试过但没用:loop: "source /home/ubuntu/anaconda3/bin/activate myCondaEnv {{ lookup('dig', 'stackoverflow.com.').split(',') }}"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
相关资源
最近更新 更多