Running packer build command as a root user

I’m building a google compute image with Packer and Ansible-Remote provisioner. Specifically, the playbooks will run as a non-root user as mentioned in the script ("ssh_username": "cloud_user")

But, the actual problem is, while I’m running this packer script via Jenkins pipeline, the jobs were running as a root user and could not consume the exported environment variables.

So, I tried to run the packer build command as below and successfully build the image, but could not consume the NEXUS credentials which is in the root user’s env variable exported by Jenkins.

sudo -iu cloud_user -- bash -c 'packer build -var-file=packer_vars.json app_build.json'

Any possible solution for the above-stated issue other than changing the DEFAULT user in Jenkins config, as this is not possible due to some other reason?

So Packer is running as root but the ansible user is not root, and needs access to environment variables?
You can use the option ansible_env_vars to inject specific environment variables into the ansible environment. As long as Packer is able to read the env vars you need, you can set them in the top-level “variables” section of your template, then use them in this section.

here’s an example:

	"variables": {
		"my_var1": {{ env `MYVAR1` }},
		"my_var2": {{ env `MYVAR2` }}
	"builders": [...],
	"provisioners": [
			"type": "ansible",
			"ansible_env_vars": ["ANSIBLE_MYVAR1={{ user `my_var1`}}", "ANSIBLE_MYVAR2={{ user `my_var2`}}"]

Alternatively, you may be able to use the command option to inject environment variables into the subprocess that calls ansible.

Hope this helps!