Programmatically Retrieve the Port Number of a Target in Boundary Using CLI

I need to automate the process of connecting to targets through scripts. Specifically, I’m looking to programmatically retrieve the port number that Boundary assigns when creating a session using the CLI command boundary connect.

I’ve tried running boundary connect -target-id= and capturing its output, but it leads to an interactive session and my script does not proceed beyond this point. Is there a method to extract the port number in a non-interactive way, suitable for integrating into a bash script or similar automation process?

Thanks.

Hello @lucardcoder
Thanks for being a boundary user.

boundary target create command supports a flag -default-client-port. This can be configured to have a predictable port that boundary assigns when creating a session during boundary connect. You can configure this port in your automation script also. Can you please see if this is helpful ?

Thanks,
Pradeep

1 Like

Hello @prsekar,

Thank you for the reply.

I will set the flag -default-client-port and try with a fixed port.

Couple follow up questions:

Does specifying a fixed port with the -default-client-port flag mean that this port is opened on my local machine each time I establish a session, or does it relate to the port usage on Boundary workers?

What happens if the specified fixed port is already in use on my local machine?

I’m trying to understand the best practices for using this feature in an automated environment and especially port assignment.

Thanks.

Specifying -default-client-port on a target means that this port will be used on your local machine when you try to establish a session (by default). If the port is already in use, I believe there will be an error thrown when you try to connect to it.

Additionally, you can also specify a -listen-port option on boundary connect to choose what port is opened on your local machine. This will override the value of -default-client-port. This allows an admin to set some default for a target, but still enables users to modify as needed.

If your goal is to execute some kind of command on a target and get its output, these commands may also be helpful to avoid getting an interactive session.

boundary connect -target-id <target_id> -exec /usr/bin/ssh -- -l <user> -i <path> -p {{boundary.port}} {{boundary.ip}} <command_to_run>

boundary connect ssh -target-id <target_id> -remote-command <command_to_run>

Example:
# Run the `hostname -i` command on a target
boundary connect -target-id ttcp_123456 -exec /usr/bin/ssh -- -l ubuntu -i /path/to/key -p {{boundary.port}} {{boundary.ip}} hostname -i
boundary connect ssh -target-id ttcp_123456 -remote-command "hostname -i"
2 Likes