'How can I turn this command into Ansible playbook?

I have a script that almost I convert into Ansible playbook. Here is an issue where I want to get the Ansible host (target) public IP address for this in the script we are doing something like this.

IP=$(dig +short myip.opendns.com @resolver1.opendns.com)

cat > /tmp/orgconfig << EOF
MSIP=$(hostname -i)
VHOST_ALIAS="${IP}:9001"
# Optionally configure TLS/SSL for virtual host.
# VHOST_SSL=y     # Set to "y" to enable TLS/SSL on the virtual host.
# KEYSTORE_JAR=   # JAR file containing the cert and private key.
# KEYSTORE_NAME=  # Name of the keystore.
# KEYSTORE_ALIAS= # The key alias.
# KEY_PASSWORD=   # The key password, if it has one.
# Specify the analytics group.
# AXGROUP=axgroup-001 # Default name is axgroup-001.
EOF

But here challenge is even I am not able to create variable like

IP=$(dig +short myip.opendns.com @resolver1.opendns.com)

and also not able to find a way to get public IP address I want to use public IP in blockinfile.



Solution 1:[1]

Regarding

I am not able to create variable like IP=$(dig +short myip.opendns.com @resolver1.opendns.com)

this can be achieved like

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Gather IP from DNS
    shell:
      cmd: dig {{ inventory_hostname }} +short
    register: IP

  - name: Show IP
    debug:
      msg: "{{ IP.stdout }}"

by Registering variables and resulting into an output of

TASK [Show IP] ***********
ok: [test1.example.com] =>
  msg: 192.0.2.1
ok: [test2.example.com] =>
  msg: 192.0.2.2

A better approach might be to use Ansible Lookup modules and dig – query DNS using the dnspython library. You may have a look into the Examples.

Regarding

... I want to use public ip in BLOCKINFILE ...

you may have a look into template – Template a file out to a target host and for syntax like VHOST_ALIAS="{{ IP.stdout }}:9001".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1