Repository: ansible-collections/community.general

Issue:
community.general.lxd connection not working with molecule
### Summary

When I try to run `molecule create` with the [lxd driver](https://github.com/ansible-community/molecule-lxd), it creates the lxc container correctly, but then gives a warning and then fails to run a command on the container.
```
[WARNING]: The "ansible_collections.community.general.plugins.connection.lxd" connection plugin has an improperly configured remote target value, forcing "inventory_hostname" templated value instead of the string
```
After some debugging, I found that the `remote_addr` value was being set to the literal string 'inventory_hostname' instead of the value of the current host's `inventory_hostname`. I found another connection plugin that had [fixed a similar issue](https://github.com/ansible/ansible/pull/77894).

Applying this patch to the `plugins/connection/lxd.py` file fixes the problem.

[fix_lxd_inventory_hostname.patch.txt](https://github.com/ansible-collections/community.general/files/8960273/fix_lxd_inventory_hostname.patch.txt)


### Issue Type

Bug Report

### Component Name

plugins/connection/lxd.py

### Ansible Version

```console (paste below)
$ ansible --version
ansible [core 2.13.1]
  config file = /home/anton/ansible-collection-oit-ne-servers/roles/common/ansible.cfg
  configured module search path = ['/home/anton/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/anton/ansible-collection-oit-ne-servers/.venv/lib/python3.10/site-packages/ansible
  ansible collection location = /home/anton/ansible-collection-oit-ne-servers/roles/common/.collections
  executable location = /home/anton/ansible-collection-oit-ne-servers/.venv/bin/ansible
  python version = 3.10.5 (main, Jun 11 2022, 16:53:24) [GCC 9.4.0]
  jinja version = 3.1.2
  libyaml = False

```


### Community.general Version

```console (paste below)
$ ansible-galaxy collection list community.general
Collection        Version
----------------- -------
community.general 5.2.0 
```


### Configuration

```console (paste below)
$ ansible-config dump --only-changed

```


### OS / Environment

cat /etc/os-release 
NAME="Ubuntu"
VERSION="20.04.4 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.4 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal

### Steps to Reproduce

<!--- Paste example playbooks or commands between quotes below -->
```console
$ mkdir tmp
$ cd tmp
$ python3 -m venv .venv
$ . .venv/bin/activate
$ python3 -m pip install --upgrade pip setuptools wheel
$ python3 -m pip install ansible molecule molecule-lxd
$ molecule init role tmp.common --driver-name lxd
$ cd common
```

Modify `molecule/default/molecule.yml`:
```yaml (paste below)
dependency:
  name: galaxy
driver:
  name: lxd
platforms:
  - name: centos-stream-8
    source:
      type: image
      mode: pull
      server: https://images.linuxcontainers.org
      protocol: simplestreams
      alias: centos/8-Stream/amd64
    profiles: ["default"]
provisioner:
  name: ansible
verifier:
  name: ansible
```

```console
$ molecule create
```

### Expected Results

I expected that the lxd container would be properly created and prepared.

### Actual Results

```console (paste below)
PLAY [Prepare] *****************************************************************

TASK [Install basic packages to bare containers] *******************************
[WARNING]: The "lxd" connection plugin has an improperly configured remote
target value, forcing "inventory_hostname" templated value instead of the
string
fatal: [centos-stream-8]: FAILED! => {"changed": true, "msg": "non-zero return code", "rc": 1, "stderr": "Error: Instance not found\n", "stderr_lines": ["Error: Instance not found"], "stdout": "", "stdout_lines": []}

```


### Code of Conduct

- [X] I agree to follow the Ansible Code of Conduct


Discussion:
Files identified in the description:
None

If these files are incorrect, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/devel/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
!component =plugins/connection/lxd.py
Files identified in the description:
* [`plugins/connection/lxd.py`](https://github.com/ansible-collections/community.general/blob/main/plugins/connection/lxd.py)

If these files are incorrect, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/devel/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @mattclay
[click here for bot help](https://github.com/ansible/ansibullbot/blob/devel/ISSUE_HELP.md)
<!--- boilerplate: notify --->
Thanks for the analysis! Would you mind creating a PR for this? (Please add a [changelog fragment](https://docs.ansible.com/ansible/devel/community/collection_development_process.html#creating-a-changelog-fragment) when creating a PR.)

Resolving patch:
diff --git a/plugins/connection/lxd.py b/plugins/connection/lxd.py
--- a/plugins/connection/lxd.py
+++ b/plugins/connection/lxd.py
@@ -18,6 +18,7 @@
             - Container identifier.
         default: inventory_hostname
         vars:
+            - name: inventory_hostname
             - name: ansible_host
             - name: ansible_lxd_host
       executable:
@@ -61,7 +62,6 @@ class Connection(ConnectionBase):
     def __init__(self, play_context, new_stdin, *args, **kwargs):
         super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
 
-        self._host = self._play_context.remote_addr
         try:
             self._lxc_cmd = get_bin_path("lxc")
         except ValueError:
@@ -75,14 +75,14 @@ def _connect(self):
         super(Connection, self)._connect()
 
         if not self._connected:
-            self._display.vvv(u"ESTABLISH LXD CONNECTION FOR USER: root", host=self._host)
+            self._display.vvv(u"ESTABLISH LXD CONNECTION FOR USER: root", host=self.get_option('remote_addr'))
             self._connected = True
 
     def exec_command(self, cmd, in_data=None, sudoable=True):
         """ execute a command on the lxd host """
         super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
 
-        self._display.vvv(u"EXEC {0}".format(cmd), host=self._host)
+        self._display.vvv(u"EXEC {0}".format(cmd), host=self.get_option('remote_addr'))
 
         local_cmd = [self._lxc_cmd]
         if self.get_option("project"):
@@ -104,10 +104,10 @@ def exec_command(self, cmd, in_data=None, sudoable=True):
         stderr = to_text(stderr)
 
         if stderr == "error: Container is not running.\n":
-            raise AnsibleConnectionFailure("container not running: %s" % self._host)
+            raise AnsibleConnectionFailure("container not running: %s" % self.get_option('remote_addr'))
 
         if stderr == "error: not found\n":
-            raise AnsibleConnectionFailure("container not found: %s" % self._host)
+            raise AnsibleConnectionFailure("container not found: %s" % self.get_option('remote_addr'))
 
         return process.returncode, stdout, stderr
 
@@ -115,7 +115,7 @@ def put_file(self, in_path, out_path):
         """ put a file from local to lxd """
         super(Connection, self).put_file(in_path, out_path)
 
-        self._display.vvv(u"PUT {0} TO {1}".format(in_path, out_path), host=self._host)
+        self._display.vvv(u"PUT {0} TO {1}".format(in_path, out_path), host=self.get_option('remote_addr'))
 
         if not os.path.isfile(to_bytes(in_path, errors='surrogate_or_strict')):
             raise AnsibleFileNotFound("input path is not a file: %s" % in_path)
@@ -138,7 +138,7 @@ def fetch_file(self, in_path, out_path):
         """ fetch a file from lxd to local """
         super(Connection, self).fetch_file(in_path, out_path)
 
-        self._display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path), host=self._host)
+        self._display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path), host=self.get_option('remote_addr'))
 
         local_cmd = [self._lxc_cmd]
         if self.get_option("project"):


Test patch: