Ignoring connection errors #1365
Replies: 2 comments 3 replies
-
|
Use |
Beta Was this translation helpful? Give feedback.
-
|
Following @Dexmachi suggestion I ended up writing something like this in a root_ssh_check_cmd = [
"ssh",
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=5",
f"root@{ip_address}",
"echo ok",
]
with open("/dev/null", "wb") as devnull:
root_ssh_available = subprocess.run(
root_ssh_check_cmd,
stdout=devnull,
stderr=devnull,
).returncode == 0
if root_ssh_available:
print("Root SSH connection is open, setting up sudo user...")
inventory = Inventory((["root_user"], {"ssh_user": "root", "ssh_hostname": ip_address}))
setup_user(inventory, username)
pyinfra_cmd = [
"pyinfra",
"-y",
ip_address,
"deploy.py",
"--user",
username,
]
subprocess.run(pyinfra_cmd, check=True)where def setup_user(inventory, username):
state = State(inventory=inventory)
connect_all(state)
sudo = "sudo"
add_op(
state,
server.packages,
name=f"Install {sudo}",
packages=[sudo],
)
groups = [sudo, "docker", "crontab"]
for group in groups:
add_op(
state,
server.group,
name=f"Create {group} group",
group=group,
)
add_op(
state,
server.user,
name="Create sudo user",
user=username,
groups=groups,
system=True,
create_home=True,
home=f"/home/{username}",
)
run_ops(state)What's missing here is the part where I disallow all root ssh connection to the server, but you get the point. This way I always ensure a sudo user exists and that it is used to run the setup. |
Beta Was this translation helpful? Give feedback.

Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to migrate from Ansible and I can't figure out this part of the puzzle:
What I'm trying to achieve
Given a server with root ssh access, as a first step before provisioning, I want to set up a non-root sudo user.
This new user should be used to do the provisioning.
Subsequent runs should not produce errors when trying to do the first step (or the connection error should be ignored).
What seems to partially work
Simplified
inventory.py:Simplified
deploy.py:Issues
This setup produces a connection error on subsequent runs:
Is there a way to maybe ignore that connection error?
Or maybe I'm approaching this the wrong way?
Beta Was this translation helpful? Give feedback.
All reactions